function logToDatabase($cbResult = null)
 {
     // CONTENTBUILDER
     global $database, $ff_config;
     $database = JFactory::getDBO();
     if ($this->dying) {
         return;
     }
     if (!is_object($cbResult['form']) && $this->editable && $this->editable_override) {
         $database->setQuery("Select id From #__facileforms_records Where form = " . $database->Quote($this->form) . " And user_id = " . $database->Quote(JFactory::getUser()->get('id', 0)) . " And user_id <> 0");
         $records = $database->loadObjectList();
         foreach ($records as $record) {
             $database->setQuery("Delete From #__facileforms_subrecords Where record = " . $record->id);
             $database->query();
             $database->setQuery("Delete From #__facileforms_records Where id = " . $record->id);
             $database->query();
         }
     }
     $record = new facileFormsRecords($database);
     $record->submitted = $this->submitted;
     $record->form = $this->form;
     $record->title = $this->formrow->title;
     $record->name = $this->formrow->name;
     $record->ip = $this->ip;
     $record->browser = $this->browser;
     $record->opsys = $this->opsys;
     $record->provider = $this->provider;
     $record->viewed = 0;
     $record->exported = 0;
     $record->archived = 0;
     if (JFactory::getUser()->get('id', 0) > 0) {
         $record->user_id = JFactory::getUser()->get('id', 0);
         $record->username = JFactory::getUser()->get('username', '');
         $record->user_full_name = JFactory::getUser()->get('name', '');
     } else {
         $record->user_id = JFactory::getUser()->get('id', 0);
         $record->username = '******';
         $record->user_full_name = '-';
     }
     // CONTENTBUILDER WILL TAKE OVER SAVING/UPDATE IF EXISTS
     $cbFileFields = array();
     if (!is_object($cbResult['form'])) {
         if (!$record->store()) {
             $this->status = _FF_STATUS_SAVERECORD_FAILED;
             $this->message = $record->getError();
             return;
         }
         // if
         $record_return = $record->id;
         if ($record_return && JFile::exists(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_contentbuilder' . DS . 'contentbuilder.xml')) {
             $last_update = JFactory::getDate();
             jimport('joomla.version');
             $version = new JVersion();
             $is3 = false;
             if (version_compare($version->getShortVersion(), '3.0', '>=')) {
                 $is3 = true;
             }
             $last_update = $is3 ? $last_update->toSql() : $last_update->toMySQL();
             $db = JFactory::getDBO();
             $db->setQuery("Select id From #__contentbuilder_records Where `type` = 'com_breezingforms' And `reference_id` = " . $db->Quote($this->form) . " And record_id = " . $db->Quote($record_return));
             $res = $db->loadResult();
             if (!$res) {
                 $db->setQuery("Insert Into #__contentbuilder_records (session_id,`type`,last_update, published, record_id, reference_id) Values ('" . JFactory::getSession()->getId() . "','com_breezingforms'," . $db->Quote($last_update) . ",0, " . $db->Quote($record_return) . ", " . $db->Quote($this->form) . ")");
                 $db->query();
             } else {
                 $db->setQuery("Update #__contentbuilder_records Set last_update = " . $db->Quote($last_update) . ",edited = edited + 1 Where `type` = 'com_breezingforms' And `reference_id` = " . $db->Quote($this->form) . " And record_id = " . $db->Quote($record_return));
                 $db->query();
             }
         }
     }
     $this->record_id = $record->id;
     $names = array();
     $subrecord = new facileFormsSubrecords($database);
     $subrecord->record = $record->id;
     if (count($this->savedata)) {
         $cbData = array();
         // CONTENTBUILDER file deletion/upgrade
         if (is_object($cbResult['form'])) {
             $db = JFactory::getDBO();
             $db->setQuery('Select SQL_CALC_FOUND_ROWS * From #__contentbuilder_forms Where id = ' . JRequest::getInt('cb_form_id', 0) . ' And published = 1');
             $_settings = $db->loadObject();
             $_record = $cbResult['form']->getRecord(JRequest::getInt('record_id', 0), $_settings->published_only, $cbResult['frontend'] ? $_settings->own_only_fe ? JFactory::getUser()->get('id', 0) : -1 : ($_settings->own_only ? JFactory::getUser()->get('id', 0) : -1), true);
             foreach ($_record as $_rec) {
                 $_files_deleted = array();
                 if ($_rec->recType == 'File Upload') {
                     $_array = JRequest::getVar('cb_delete_' . $_rec->recElementId, array(), '', 'ARRAY');
                     foreach ($_array as $_key => $_arr) {
                         if ($_arr == 1) {
                             $_values = explode("\n", $_rec->recValue);
                             if (isset($_values[$_key])) {
                                 if (strpos(strtolower($_values[$_key]), '{cbsite}') === 0) {
                                     $_values[$_key] = str_replace(array('{cbsite}', '{CBSite}'), array(JPATH_SITE, JPATH_SITE), $_values[$_key]);
                                 }
                                 if (JFile::exists($_values[$_key])) {
                                     JFile::delete($_values[$_key]);
                                 }
                                 if (!isset($_files_deleted[$_rec->recElementId])) {
                                     $_files_deleted[$_rec->recElementId] = array();
                                 }
                                 $_files_deleted[$_rec->recElementId][] = $_key;
                             }
                         }
                     }
                     if (isset($_files_deleted[$_rec->recElementId]) && is_array($_files_deleted[$_rec->recElementId]) && count($_files_deleted[$_rec->recElementId])) {
                         $_i = 0;
                         foreach ($this->savedata as $data) {
                             if ($data[_FF_DATA_ID] == $_rec->recElementId) {
                                 $_is_values = explode("\n", $_rec->recValue);
                                 $_j = 0;
                                 foreach ($_is_values as $_is_value) {
                                     if (!in_array($_j, $_files_deleted[$_rec->recElementId])) {
                                         $this->savedata[$_i][_FF_DATA_VALUE] .= $_is_value . "\n";
                                     }
                                     $_j++;
                                 }
                                 $this->savedata[$_i][_FF_DATA_VALUE] = rtrim($this->savedata[$_i][_FF_DATA_VALUE]);
                                 break;
                             }
                             $_i++;
                         }
                     } else {
                         if (true) {
                             $next = count($this->savedata);
                             $this->savedata[$next] = array();
                             $this->savedata[$next][_FF_DATA_ID] = $_rec->recElementId;
                             $this->savedata[$next][_FF_DATA_NAME] = $_rec->recName;
                             $this->savedata[$next][_FF_DATA_TITLE] = $_rec->recTitle;
                             $this->savedata[$next][_FF_DATA_TYPE] = $_rec->recType;
                             $this->savedata[$next][_FF_DATA_VALUE] = '';
                             $_is_values = explode("\n", $_rec->recValue);
                             foreach ($_is_values as $_is_value) {
                                 $this->savedata[$next][_FF_DATA_VALUE] .= $_is_value . "\n";
                             }
                             $this->savedata[$next][_FF_DATA_VALUE] = rtrim($this->savedata[$next][_FF_DATA_VALUE]);
                         }
                     }
                 }
             }
         }
         $_savedata = array();
         if (!is_object($cbResult['form'])) {
             foreach ($this->savedata as $data) {
                 if ($data[_FF_DATA_TYPE] == 'File Upload') {
                     if (!isset($_savedata[$data[_FF_DATA_ID]])) {
                         $_savedata[$data[_FF_DATA_ID]] = '';
                     }
                     $_savedata[$data[_FF_DATA_ID]] .= $data[_FF_DATA_VALUE] . "\n";
                 }
             }
         }
         $isset = array();
         foreach ($this->savedata as $data) {
             // CONTENTBUILDER WILL TAKE OVER SAVING/UPDATE IF EXISTS
             if (!is_object($cbResult['form'])) {
                 $subrecord->id = NULL;
                 $subrecord->element = $data[_FF_DATA_ID];
                 $subrecord->name = $data[_FF_DATA_NAME];
                 $subrecord->title = $data[_FF_DATA_TITLE];
                 $subrecord->type = $data[_FF_DATA_TYPE];
                 if (isset($_savedata[$data[_FF_DATA_ID]]) && !isset($isset[$data[_FF_DATA_ID]])) {
                     $subrecord->value = trim($_savedata[$data[_FF_DATA_ID]]);
                 } else {
                     $subrecord->value = $data[_FF_DATA_VALUE];
                 }
                 if (!isset($isset[$data[_FF_DATA_ID]])) {
                     if (!$subrecord->store()) {
                         $this->status = _FF_STATUS_SAVESUBRECORD_FAILED;
                         $this->message = $subrecord->getError();
                         return;
                     }
                 }
                 if ($data[_FF_DATA_TYPE] == 'File Upload') {
                     $isset[$data[_FF_DATA_ID]] = true;
                 }
             } else {
                 require_once JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_contentbuilder' . DS . 'classes' . DS . 'contentbuilder.php';
                 $cbNonEditableFields = contentbuilder::getListNonEditableElements($cbResult['data']['id']);
                 if (!in_array($data[_FF_DATA_ID], $cbNonEditableFields)) {
                     switch ($data[_FF_DATA_TYPE]) {
                         case 'Checkbox':
                         case 'Checkbox Group':
                         case 'Radio Button':
                         case 'Radio Group':
                         case 'Select List':
                             if (!isset($cbData[$data[_FF_DATA_ID]])) {
                                 $cbData[$data[_FF_DATA_ID]] = array();
                             }
                             $cbData[$data[_FF_DATA_ID]][] = $data[_FF_DATA_VALUE];
                             break;
                         case 'File Upload':
                             if (!isset($cbData[$data[_FF_DATA_ID]])) {
                                 $cbData[$data[_FF_DATA_ID]] = '';
                                 $cbFileFields[] = $data[_FF_DATA_ID];
                             }
                             $cbData[$data[_FF_DATA_ID]] .= $data[_FF_DATA_VALUE] . "\n";
                             break;
                         default:
                             $cbData[$data[_FF_DATA_ID]] = $data[_FF_DATA_VALUE];
                     }
                 }
             }
         }
         // foreach
         // CONTENTBUILDER BEGIN
         if (is_object($cbResult['form'])) {
             JPluginHelper::importPlugin('contentbuilder_submit');
             $submit_dispatcher = JDispatcher::getInstance();
             jimport('joomla.version');
             $version = new JVersion();
             $is15 = true;
             if (version_compare($version->getShortVersion(), '1.6', '>=')) {
                 $is15 = false;
             }
             $values = array();
             $names = $cbResult['form']->getAllElements();
             foreach ($names as $id => $name) {
                 if (isset($cbData[$id])) {
                     if (in_array($id, $cbFileFields) && trim($cbData[$id]) == '') {
                         $values[$id] = '';
                     } else {
                         if (in_array($id, $cbFileFields) && trim($cbData[$id]) != '') {
                             $values[$id] = trim($cbData[$id]);
                         } else {
                             $values[$id] = $cbData[$id];
                         }
                     }
                 }
             }
             $submit_before_result = $submit_dispatcher->trigger('onBeforeSubmit', array(JRequest::getInt('cb_record_id', 0), $cbResult['form'], $values));
             $record_return = $cbResult['form']->saveRecord(JRequest::getInt('cb_record_id', 0), $values);
             $db = JFactory::getDBO();
             $db->setQuery('Select SQL_CALC_FOUND_ROWS * From #__contentbuilder_forms Where id = ' . JRequest::getInt('cb_form_id', 0) . ' And published = 1');
             $cbData = $db->loadObject();
             if ($record_return) {
                 $this->record_id = $record_return;
                 $sef = '';
                 $ignore_lang_code = '*';
                 if ($cbResult['data']['default_lang_code_ignore']) {
                     jimport('joomla.version');
                     $version = new JVersion();
                     if (version_compare($version->getShortVersion(), '1.6', '>=')) {
                         $db->setQuery("Select lang_code From #__languages Where published = 1 And sef = " . $db->Quote(trim(JRequest::getCmd('lang', ''))));
                         $ignore_lang_code = $db->loadResult();
                         if (!$ignore_lang_code) {
                             $ignore_lang_code = '*';
                         }
                     } else {
                         $codes = contentbuilder::getLanguageCodes();
                         foreach ($codes as $code) {
                             if (strstr(strtolower($code), strtolower(trim(JRequest::getCmd('lang', '')))) !== false) {
                                 $ignore_lang_code = strtolower($code);
                                 break;
                             }
                         }
                     }
                     $sef = trim(JRequest::getCmd('lang', ''));
                     if ($ignore_lang_code == '*') {
                         $sef = '';
                     }
                 } else {
                     jimport('joomla.version');
                     $version = new JVersion();
                     if (version_compare($version->getShortVersion(), '1.6', '>=')) {
                         $db->setQuery("Select sef From #__languages Where published = 1 And lang_code = " . $db->Quote($cbResult['data']['default_lang_code']));
                         $sef = $db->loadResult();
                     } else {
                         $codes = contentbuilder::getLanguageCodes();
                         foreach ($codes as $code) {
                             if ($code == $cbResult['data']['default_lang_code']) {
                                 $sef = explode('-', $code);
                                 if (count($sef)) {
                                     $sef = strtolower($sef[0]);
                                 }
                                 break;
                             }
                         }
                     }
                 }
                 $language = $cbResult['data']['default_lang_code_ignore'] ? $ignore_lang_code : $cbResult['data']['default_lang_code'];
                 $db->setQuery("Select id From #__contentbuilder_records Where `type` = 'com_breezingforms' And `reference_id` = " . $db->Quote($cbResult['form']->getReferenceId()) . " And record_id = " . $db->Quote($record_return));
                 $res = $db->loadResult();
                 $last_update = JFactory::getDate();
                 $version = new JVersion();
                 $is3 = false;
                 if (version_compare($version->getShortVersion(), '3.0', '>=')) {
                     $is3 = true;
                 }
                 $last_update = $is3 ? $last_update->toSql() : $last_update->toMySQL();
                 if (!$res) {
                     $is_future = 0;
                     $created_up = JFactory::getDate();
                     $created_up = $is3 ? $created_up->toSql() : $created_up->toMySQL();
                     if (intval($cbData->default_publish_up_days) != 0) {
                         $is_future = 1;
                         $date = JFactory::getDate(strtotime('now +' . intval($cbData->default_publish_up_days) . ' days'));
                         $created_up = $is3 ? $date->toSql() : $date->toMySQL();
                     }
                     $created_down = '0000-00-00 00:00:00';
                     if (intval($cbData->default_publish_down_days) != 0) {
                         $date = JFactory::getDate(strtotime($created_up . ' +' . intval($cbData->default_publish_down_days) . ' days'));
                         $created_down = $is3 ? $date->toSql() : $date->toMySQL();
                     }
                     $db->setQuery("Insert Into #__contentbuilder_records (session_id,`type`,last_update,is_future,lang_code, sef, published, record_id, reference_id, publish_up, publish_down) Values ('" . JFactory::getSession()->getId() . "','com_breezingforms'," . $db->Quote($last_update) . ",{$is_future}, " . $db->Quote($language) . "," . $db->Quote(trim($sef)) . "," . $db->Quote($cbData->auto_publish && !$is_future ? 1 : 0) . ", " . $db->Quote($record_return) . ", " . $db->Quote($cbResult['form']->getReferenceId()) . ", " . $db->Quote($created_up) . ", " . $db->Quote($created_down) . ")");
                     $db->query();
                 } else {
                     $db->setQuery("Update #__contentbuilder_records Set last_update = " . $db->Quote($last_update) . ",lang_code = " . $db->Quote($language) . ", sef = " . $db->Quote(trim($sef)) . ", edited = edited + 1 Where `type` = 'com_breezingforms' And `reference_id` = " . $db->Quote($cbResult['form']->getReferenceId()) . " And record_id = " . $db->Quote($record_return));
                     $db->query();
                 }
             }
             $article_id = 0;
             // creating the article
             if (is_object($cbData) && $cbData->create_articles) {
                 JRequest::setVar('cb_category_id', null);
                 JRequest::setVar('cb_controller', null);
                 jimport('joomla.version');
                 $version = new JVersion();
                 if (JFactory::getApplication()->isSite() && JRequest::getInt('Itemid', 0)) {
                     if (version_compare($version->getShortVersion(), '1.6', '>=')) {
                         $menu = JSite::getMenu();
                         $item = $menu->getActive();
                         if (is_object($item)) {
                             JRequest::setVar('cb_category_id', $item->params->get('cb_category_id', null));
                             JRequest::setVar('cb_controller', $item->params->get('cb_controller', null));
                         }
                     } else {
                         $params = JComponentHelper::getParams('com_contentbuilder');
                         JRequest::setVar('cb_category_id', $params->get('cb_category_id', null));
                         JRequest::setVar('cb_controller', $params->get('cb_controller', null));
                     }
                 }
                 $cbData->page_title = $cbData->use_view_name_as_title ? $cbData->name : $cbResult['form']->getPageTitle();
                 $cbData->labels = $cbResult['form']->getElementLabels();
                 $ids = array();
                 foreach ($cbData->labels as $reference_id => $label) {
                     $ids[] = $db->Quote($reference_id);
                 }
                 $cbData->labels = array();
                 if (count($ids)) {
                     $db->setQuery("Select Distinct `label`, reference_id From #__contentbuilder_elements Where form_id = " . JRequest::getInt('cb_form_id', 0) . " And reference_id In (" . implode(',', $ids) . ") And published = 1 Order By ordering");
                     $rows = $db->loadAssocList();
                     $ids = array();
                     foreach ($rows as $row) {
                         $ids[] = $row['reference_id'];
                     }
                 }
                 $cbData->items = $cbResult['form']->getRecord($record_return, $cbData->published_only, $cbResult['frontend'] ? $cbData->own_only_fe ? JFactory::getUser()->get('id', 0) : -1 : ($cbData->own_only ? JFactory::getUser()->get('id', 0) : -1), true);
                 if (!count($cbData->items)) {
                     JError::raiseError(404, JText::_('COM_CONTENTBUILDER_RECORD_NOT_FOUND'));
                 }
                 $config = array();
                 $full = false;
                 $article_id = contentbuilder::createArticle(JRequest::getInt('cb_form_id', 0), $record_return, $cbData->items, $ids, $cbData->title_field, $cbResult['form']->getRecordMetadata($record_return), $config, $full, true, JRequest::getVar('cb_category_id', null));
                 $cache = JFactory::getCache('com_content');
                 $cache->clean();
                 $cache = JFactory::getCache('com_contentbuilder');
                 $cache->clean();
             }
             $submit_after_result = $submit_dispatcher->trigger('onAfterSubmit', array($record_return, $article_id, $cbResult['form'], $values));
         }
         // CONTENTBUILDER END
         // joomla 3 tagging
         $db = JFactory::getDBO();
         jimport('joomla.version');
         $version = new JVersion();
         if (version_compare($version->getShortVersion(), '3.1', '>=') && $this->formrow->tags_content != '') {
             $title = '';
             $tags_body = '';
             if (trim($this->formrow->tags_content_template) == '') {
                 $lol = 0;
                 $tags_body = '<ul class="category list-striped list-condensed">' . "\n";
                 foreach ($this->savedata as $data) {
                     if ($data[_FF_DATA_ID] == $this->formrow->tags_content_template_default_element) {
                         $title = $data[_FF_DATA_VALUE];
                     }
                     if ($lol == 1) {
                         $lol = 0;
                     }
                     $tagvalue = '';
                     if (is_array($data[_FF_DATA_VALUE])) {
                         $tagvalue = implode(', ', $data[_FF_DATA_VALUE]);
                     } else {
                         $tagvalue = $data[_FF_DATA_VALUE];
                     }
                     $tagvalue = bf_cleanString($tagvalue);
                     $tags_body .= '<li class="cat-list-row' . $lol . '"><strong class="list-title">' . htmlentities($data[_FF_DATA_TITLE], ENT_QUOTES, 'UTF-8') . '</strong><div>' . htmlentities($tagvalue, ENT_QUOTES, 'UTF-8') . '</div></li>' . "\n";
                     $lol++;
                 }
                 $tags_body .= '</ul>' . "\n";
             } else {
                 $tags_body = $this->formrow->tags_content_template;
                 foreach ($this->savedata as $data) {
                     if ($data[_FF_DATA_ID] == $this->formrow->tags_content_template_default_element) {
                         $title = $data[_FF_DATA_VALUE];
                     }
                     $tagvalue = '';
                     if (is_array($data[_FF_DATA_VALUE])) {
                         $tagvalue = implode(', ', $data[_FF_DATA_VALUE]);
                     } else {
                         $tagvalue = $data[_FF_DATA_VALUE];
                     }
                     $tagvalue = bf_cleanString($tagvalue);
                     $tags_body = str_replace('{' . $data[_FF_DATA_NAME] . ':label}', htmlentities($data[_FF_DATA_TITLE], ENT_QUOTES, 'UTF-8'), $tags_body);
                     $tags_body = str_replace('{' . $data[_FF_DATA_NAME] . ':value}', htmlentities($tagvalue, ENT_QUOTES, 'UTF-8'), $tags_body);
                 }
                 $matches = array();
                 preg_match_all("/\\{BFImageScale([^}]*)\\}/i", $tags_body, $matches);
                 if (isset($matches[0]) && isset($matches[1]) && is_array($matches[1]) && count($matches[1]) > 0) {
                     $i = 0;
                     foreach ($matches[1] as $match) {
                         $options = explode(';', trim($match));
                         $options_length = count($options);
                         for ($x = 0; $x < $options_length; $x++) {
                             $options[$x] = trim($options[$x]);
                             if ($options[$x] == '') {
                                 unset($options[$x]);
                             }
                         }
                         $options[] = 'record-id: ' . $this->record_id;
                         $options[] = 'form-id: ' . $this->form;
                         $out = implode('; ', $options);
                         $tags_body = str_replace($matches[0][$i], '{BFImageScale ' . $out . '}', $tags_body);
                         $i++;
                     }
                 }
                 $matches = array();
                 preg_match_all("/\\{BFDownload([^}]*)\\}/i", $tags_body, $matches);
                 if (isset($matches[0]) && isset($matches[1]) && is_array($matches[1]) && count($matches[1]) > 0) {
                     $i = 0;
                     foreach ($matches[1] as $match) {
                         $options = explode(';', trim($match));
                         $options_length = count($options);
                         for ($x = 0; $x < $options_length; $x++) {
                             $options[$x] = trim($options[$x]);
                             if ($options[$x] == '') {
                                 unset($options[$x]);
                             }
                         }
                         $options[] = 'record-id: ' . $this->record_id;
                         $options[] = 'form-id: ' . $this->form;
                         $out = implode('; ', $options);
                         $tags_body = str_replace($matches[0][$i], '{BFDownload ' . $out . '}', $tags_body);
                         $i++;
                     }
                 }
             }
             if (trim($title) == '' && isset($this->savedata[0])) {
                 $title = $this->savedata[0][_FF_DATA_TITLE];
             } else {
                 if (trim($title) == '' && !isset($this->savedata[0])) {
                     $title = 'Unknown';
                 }
             }
             $tag_date = JFactory::getDate();
             // Clean text for xhtml transitional compliance
             $introtext = '';
             $fulltext = '';
             $tags_body = str_replace('<br>', '<br />', $tags_body);
             // Search for the {readmore} tag and split the text up accordingly.
             $pattern = '#<hr\\s+id=("|\')system-readmore("|\')\\s*\\/*>#i';
             $tagPos = preg_match($pattern, $tags_body);
             if ($tagPos == 0) {
                 $introtext = $tags_body;
             } else {
                 list($introtext, $fulltext) = preg_split($pattern, $tags_body, 2);
             }
             $db->setQuery("Insert Into \n                    #__content \n                        (\n                         `title`,\n                         `alias`,\n                         `introtext`,\n                         `fulltext`,\n                         `state`,\n                         `catid`,\n                         `created`,\n                         `created_by`,\n                         `modified`,\n                         `modified_by`,\n                         `checked_out`,\n                         `checked_out_time`,\n                         `publish_up`,\n                         `publish_down`,\n                         `attribs`,\n                         `version`,\n                         `metakey`,\n                         `metadesc`,\n                         `metadata`,\n                         `access`,\n                         `created_by_alias`,\n                         `language`,\n                         `featured`\n                        ) \n                    Values \n                        (\n                          " . $db->quote($title) . ",\n                          " . $db->quote(bf_stringURLUnicodeSlug($item_id . '-' . $title)) . ",\n                          " . $db->quote($introtext) . ",\n                          " . $db->quote($fulltext) . ",\n                          " . intval($this->formrow->tags_content_default_state) . ",\n                          " . intval($this->formrow->tags_content_default_category) . ",\n                          '" . $tag_date->toSql() . "',\n                          " . $db->quote(JFactory::getUser()->get('id', 0)) . ",\n                          '" . $tag_date->toSql() . "',\n                          " . $db->quote(JFactory::getUser()->get('id', 0)) . ",\n                          '0',\n                          '0000-00-00 00:00:00',\n                          '" . ($this->formrow->tags_content_default_publishup == '' || $this->formrow->tags_content_default_publishup == '0000-00-00 00:00:00' ? $tag_date->toSql() : $this->formrow->tags_content_default_publishup) . "',\n                          '" . ($this->formrow->tags_content_default_publishdown == '' || $this->formrow->tags_content_default_publishdown == '0000-00-00 00:00:00' ? '0000-00-00 00:00:00' : $this->formrow->tags_content_default_publishdown) . "',\n                          '',\n                          '1',\n                          '',\n                          '',\n                          '',\n                          " . intval($this->formrow->tags_content_default_access) . ",\n                          " . $db->quote(JFactory::getUser()->get('username', 'Anonymous')) . ",\n                          " . $db->quote($this->formrow->tags_content_default_language) . ",\n                          " . intval($this->formrow->tags_content_default_featured) . "\n                       )\n                ");
             $db->query();
             $item_id = $db->insertid();
             JFactory::getDbo()->setQuery("Select type_id From #__content_types Where type_alias = 'com_content.article'");
             $tag_typeid = JFactory::getDbo()->loadResult();
             $db->setQuery("Insert Into #__ucm_content (\n                    core_catid,\n                    core_content_item_id,\n                    core_type_alias, \n                    core_title, \n                    core_alias, \n                    core_body, \n                    core_created_time,\n                    core_modified_time,\n                    core_created_user_id,\n                    core_created_by_alias,\n                    core_modified_user_id,\n                    core_state,\n                    core_access,\n                    core_language,\n                    core_type_id,\n                    core_featured,\n                    core_publish_up,\n                    core_publish_down\n                 ) Values (\n                    " . intval($this->formrow->tags_content_default_category) . ",\n                    '" . $item_id . "',\n                    'com_content.article',\n                    " . $db->quote($title) . ",\n                    " . $db->quote(bf_stringURLUnicodeSlug($title)) . ",\n                    " . $db->quote($tags_body) . ",\n                    '" . $tag_date->toSql() . "',\n                    '" . $tag_date->toSql() . "',\n                    " . $db->quote(JFactory::getUser()->get('id', 0)) . ",\n                    " . $db->quote(JFactory::getUser()->get('username', 'Anonymous')) . ",\n                    " . $db->quote(JFactory::getUser()->get('id', 0)) . ",\n                    " . intval($this->formrow->tags_content_default_state) . ",\n                    " . intval($this->formrow->tags_content_default_access) . ",\n                    " . $db->quote($this->formrow->tags_content_default_language) . ",\n                    " . intval($tag_typeid) . ",\n                    " . intval($this->formrow->tags_content_default_featured) . ",\n                    '" . ($this->formrow->tags_content_default_publishup == '' || $this->formrow->tags_content_default_publishup == '0000-00-00 00:00:00' ? $tag_date->toSql() : $this->formrow->tags_content_default_publishup) . "',\n                    '" . ($this->formrow->tags_content_default_publishdown == '' || $this->formrow->tags_content_default_publishdown == '0000-00-00 00:00:00' ? '0000-00-00 00:00:00' : $this->formrow->tags_content_default_publishdown) . "'\n                 )");
             $db->query();
             $ucm_id = $db->insertid();
             JFactory::getDbo()->setQuery("Select lang_id From #__languages Where lang_code=" . $db->quote($this->formrow->tags_content_default_language));
             $lang_id = JFactory::getDbo()->loadColumn();
             JFactory::getDbo()->setQuery("Insert Into #__ucm_base (\n                    ucm_id, \n                    ucm_item_id, \n                    ucm_type_id, \n                    ucm_language_id\n                 ) Values (\n                    " . $ucm_id . ",\n                    " . $item_id . ",\n                    " . intval($tag_typeid) . ",\n                    " . ($lang_id ? intval($lang_id) : 0) . "\n                 )");
             JFactory::getDbo()->query();
             $tags_content = explode(',', $this->formrow->tags_content);
             JArrayHelper::toInteger($tags_content);
             foreach ($tags_content as $tags_content_entry) {
                 JFactory::getDbo()->setQuery("Insert Into #__contentitem_tag_map (\n                        type_alias, \n                        core_content_id, \n                        content_item_id, \n                        tag_id, \n                        tag_date, \n                        type_id\n                     ) Values (\n                        'com_content.article',\n                        " . $ucm_id . ",\n                        " . $item_id . ",\n                        " . $tags_content_entry . ",\n                        '" . $tag_date->toSql() . "',\n                        " . $tag_typeid . "\n                     )");
                 try {
                     JFactory::getDbo()->query();
                 } catch (Exception $e) {
                 }
             }
         }
         // joomla 3 tagging end
     }
     require_once JPATH_SITE . '/administrator/components/com_breezingforms/libraries/crosstec/classes/BFIntegrate.php';
     $integrate = new BFIntegrate($this->form);
     if (count($this->savedata)) {
         foreach ($this->savedata as $data) {
             $integrate->field($data);
         }
     }
     $integrate->commit();
     if (isset($record_return)) {
         return $record_return;
     }
 }
Exemple #2
0
 function store()
 {
     JRequest::checkToken('default') or jexit(JText::_('JInvalid_Token'));
     JPluginHelper::importPlugin('contentbuilder_submit');
     $submit_dispatcher = JDispatcher::getInstance();
     JFactory::getSession()->clear('cb_failed_values', 'com_contentbuilder.' . $this->_id);
     JRequest::setVar('cb_submission_failed', 0);
     $query = $this->_buildQuery();
     $this->_data = $this->_getList($query, 0, 1);
     if (!count($this->_data)) {
         JError::raiseError(404, JText::_('COM_CONTENTBUILDER_FORM_NOT_FOUND'));
     }
     foreach ($this->_data as $data) {
         if (!$this->frontend && $data->display_in == 0) {
             JError::raiseError(404, JText::_('COM_CONTENTBUILDER_RECORD_NOT_FOUND'));
         } else {
             if ($this->frontend && $data->display_in == 1) {
                 JError::raiseError(404, JText::_('COM_CONTENTBUILDER_RECORD_NOT_FOUND'));
             }
         }
         $data->form_id = $this->_id;
         if ($data->type && $data->reference_id) {
             $values = array();
             $data->form = contentbuilder::getForm($data->type, $data->reference_id);
             $meta = $data->form->getRecordMetadata($this->_record_id);
             if (!$data->edit_by_type) {
                 $noneditable_fields = contentbuilder::getListNonEditableElements($this->_id);
                 $names = $data->form->getElementNames();
                 $this->_db->setQuery("Select * From #__contentbuilder_elements Where form_id = " . $this->_id . " And published = 1 And editable = 1");
                 $fields = $this->_db->loadAssocList();
                 $the_fields = array();
                 $the_name_field = null;
                 $the_username_field = null;
                 $the_password_field = null;
                 $the_password_repeat_field = null;
                 $the_email_field = null;
                 $the_email_repeat_field = null;
                 $the_html_fields = array();
                 $the_upload_fields = array();
                 $the_captcha_field = null;
                 $the_failed_registration_fields = array();
                 jimport('joomla.filesystem.file');
                 jimport('joomla.filesystem.folder');
                 foreach ($fields as $special_field) {
                     switch ($special_field['type']) {
                         case 'text':
                         case 'upload':
                         case 'captcha':
                         case 'textarea':
                             if ($special_field['type'] == 'upload') {
                                 $options = unserialize(base64_decode($special_field['options']));
                                 $special_field['options'] = $options;
                                 $the_upload_fields[$special_field['reference_id']] = $special_field;
                             } else {
                                 if ($special_field['type'] == 'captcha') {
                                     $options = unserialize(base64_decode($special_field['options']));
                                     $special_field['options'] = $options;
                                     $the_captcha_field = $special_field;
                                 } else {
                                     if ($special_field['type'] == 'textarea') {
                                         $options = unserialize(base64_decode($special_field['options']));
                                         $special_field['options'] = $options;
                                         if (isset($special_field['options']->allow_html) && $special_field['options']->allow_html) {
                                             $the_html_fields[$special_field['reference_id']] = $special_field;
                                         } else {
                                             $the_fields[$special_field['reference_id']] = $special_field;
                                         }
                                     } else {
                                         if ($special_field['type'] == 'text') {
                                             $options = unserialize(base64_decode($special_field['options']));
                                             $special_field['options'] = $options;
                                             if ($data->act_as_registration && $data->registration_username_field == $special_field['reference_id']) {
                                                 $the_username_field = $special_field;
                                             } else {
                                                 if ($data->act_as_registration && $data->registration_name_field == $special_field['reference_id']) {
                                                     $the_name_field = $special_field;
                                                 } else {
                                                     if ($data->act_as_registration && $data->registration_password_field == $special_field['reference_id']) {
                                                         $the_password_field = $special_field;
                                                     } else {
                                                         if ($data->act_as_registration && $data->registration_password_repeat_field == $special_field['reference_id']) {
                                                             $the_password_repeat_field = $special_field;
                                                         } else {
                                                             if ($data->act_as_registration && $data->registration_email_field == $special_field['reference_id']) {
                                                                 $the_email_field = $special_field;
                                                             } else {
                                                                 if ($data->act_as_registration && $data->registration_email_repeat_field == $special_field['reference_id']) {
                                                                     $the_email_repeat_field = $special_field;
                                                                 } else {
                                                                     $the_fields[$special_field['reference_id']] = $special_field;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             break;
                         default:
                             $options = unserialize(base64_decode($special_field['options']));
                             $special_field['options'] = $options;
                             $the_fields[$special_field['reference_id']] = $special_field;
                     }
                 }
                 // we have defined a captcha, so let's test it
                 if ($the_captcha_field !== null && !in_array($the_captcha_field['reference_id'], $noneditable_fields)) {
                     if (!class_exists('Securimage')) {
                         require_once JPATH_SITE . DS . 'components' . DS . 'com_contentbuilder' . DS . 'images' . DS . 'securimage' . DS . 'securimage.php';
                     }
                     $securimage = new Securimage();
                     $cap_value = JRequest::getVar('cb_' . $the_captcha_field['reference_id'], null, 'POST');
                     if ($securimage->check($cap_value) == false) {
                         JRequest::setVar('cb_submission_failed', 1);
                         JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_CAPTCHA_FAILED'), 'error');
                     }
                     $values[$the_captcha_field['reference_id']] = $cap_value;
                     $noneditable_fields[] = $the_captcha_field['reference_id'];
                 }
                 // now let us see if we have a registration
                 // make sure to wait for previous errors
                 if ($data->act_as_registration && $the_name_field !== null && $the_email_field !== null && $the_email_repeat_field !== null && $the_password_field !== null && $the_password_repeat_field !== null && $the_username_field !== null) {
                     $pw1 = JRequest::getVar('cb_' . $the_password_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW);
                     $pw2 = JRequest::getVar('cb_' . $the_password_repeat_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW);
                     $email = JRequest::getVar('cb_' . $the_email_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW);
                     $email2 = JRequest::getVar('cb_' . $the_email_repeat_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW);
                     $name = JRequest::getVar('cb_' . $the_name_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW);
                     $username = JRequest::getVar('cb_' . $the_username_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW);
                     if (!JRequest::getVar('cb_submission_failed', 0)) {
                         if (!trim($name)) {
                             JRequest::setVar('cb_submission_failed', 1);
                             JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_NAME_EMPTY'), 'error');
                         }
                         if (!trim($username)) {
                             JRequest::setVar('cb_submission_failed', 1);
                             JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_USERNAME_EMPTY'), 'error');
                         } else {
                             if (preg_match("#[<>\"'%;()&]#i", $username) || strlen(utf8_decode($username)) < 2) {
                                 JRequest::setVar('cb_submission_failed', 1);
                                 JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_USERNAME_INVALID'), 'error');
                             }
                         }
                         if (!trim($email)) {
                             JRequest::setVar('cb_submission_failed', 1);
                             JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_EMAIL_EMPTY'), 'error');
                         } else {
                             if (!contentbuilder_is_email($email)) {
                                 JRequest::setVar('cb_submission_failed', 1);
                                 JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_EMAIL_INVALID'), 'error');
                             } else {
                                 if ($email != $email2) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_EMAIL_MISMATCH'), 'error');
                                 }
                             }
                         }
                         if (!$meta->created_id && !JFactory::getUser()->get('id', 0)) {
                             $this->_db->setQuery("Select count(id) From #__users Where `username` = " . $this->_db->Quote($username));
                             if ($this->_db->loadResult()) {
                                 JRequest::setVar('cb_submission_failed', 1);
                                 JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_USERNAME_NOT_AVAILABLE'), 'error');
                             }
                             $this->_db->setQuery("Select count(id) From #__users Where `email` = " . $this->_db->Quote($email));
                             if ($this->_db->loadResult()) {
                                 JRequest::setVar('cb_submission_failed', 1);
                                 JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_EMAIL_NOT_AVAILABLE'), 'error');
                             }
                             if ($pw1 != $pw2) {
                                 JRequest::setVar('cb_submission_failed', 1);
                                 JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_PASSWORD_MISMATCH'), 'error');
                                 JRequest::setVar('cb_' . $the_password_field['reference_id'], '');
                                 JRequest::setVar('cb_' . $the_password_repeat_field['reference_id'], '');
                             } else {
                                 if (!trim($pw1)) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_PASSWORD_EMPTY'), 'error');
                                     JRequest::setVar('cb_' . $the_password_field['reference_id'], '');
                                     JRequest::setVar('cb_' . $the_password_repeat_field['reference_id'], '');
                                 }
                             }
                         } else {
                             if ($meta->created_id && $meta->created_id != JFactory::getUser()->get('id', 0)) {
                                 $this->_db->setQuery("Select count(id) From #__users Where id <> " . $this->_db->Quote($meta->created_id) . " And `username` = " . $this->_db->Quote($username));
                                 if ($this->_db->loadResult()) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_USERNAME_NOT_AVAILABLE'), 'error');
                                 }
                                 $this->_db->setQuery("Select count(id) From #__users Where id <> " . $this->_db->Quote($meta->created_id) . " And `email` = " . $this->_db->Quote($email));
                                 if ($this->_db->loadResult()) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_EMAIL_NOT_AVAILABLE'), 'error');
                                 }
                             } else {
                                 $this->_db->setQuery("Select count(id) From #__users Where id <> " . $this->_db->Quote(JFactory::getUser()->get('id', 0)) . " And `username` = " . $this->_db->Quote($username));
                                 if ($this->_db->loadResult()) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_USERNAME_NOT_AVAILABLE'), 'error');
                                 }
                                 $this->_db->setQuery("Select count(id) From #__users Where id <> " . $this->_db->Quote(JFactory::getUser()->get('id', 0)) . " And `email` = " . $this->_db->Quote($email));
                                 if ($this->_db->loadResult()) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_EMAIL_NOT_AVAILABLE'), 'error');
                                 }
                             }
                             if (trim($pw1) != '' || trim($pw2) != '') {
                                 if ($pw1 != $pw2) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_PASSWORD_MISMATCH'), 'error');
                                     JRequest::setVar('cb_' . $the_password_field['reference_id'], '');
                                     JRequest::setVar('cb_' . $the_password_repeat_field['reference_id'], '');
                                 } else {
                                     if (!trim($pw1)) {
                                         JRequest::setVar('cb_submission_failed', 1);
                                         JFactory::getApplication()->enqueueMessage(JText::_('COM_CONTENTBUILDER_PASSWORD_EMPTY'), 'error');
                                         JRequest::setVar('cb_' . $the_password_field['reference_id'], '');
                                         JRequest::setVar('cb_' . $the_password_repeat_field['reference_id'], '');
                                     }
                                 }
                             }
                         }
                         if (!JRequest::getVar('cb_submission_failed', 0)) {
                             //$noneditable_fields[] = $the_name_field['reference_id'];
                             $noneditable_fields[] = $the_password_field['reference_id'];
                             $noneditable_fields[] = $the_password_repeat_field['reference_id'];
                             //$noneditable_fields[] = $the_email_field['reference_id'];
                             $noneditable_fields[] = $the_email_repeat_field['reference_id'];
                             //$noneditable_fields[] = $the_username_field['reference_id'];
                         } else {
                             $the_failed_registration_fields[$the_name_field['reference_id']] = $the_name_field;
                             //$the_failed_registration_fields[$the_password_field['reference_id']] = $the_password_field;
                             //$the_failed_registration_fields[$the_password_repeat_field['reference_id']] = $the_password_repeat_field;
                             $the_failed_registration_fields[$the_email_field['reference_id']] = $the_email_field;
                             $the_failed_registration_fields[$the_email_repeat_field['reference_id']] = $the_email_repeat_field;
                             $the_failed_registration_fields[$the_username_field['reference_id']] = $the_username_field;
                         }
                     } else {
                         $the_failed_registration_fields[$the_name_field['reference_id']] = $the_name_field;
                         //$the_failed_registration_fields[$the_password_field['reference_id']] = $the_password_field;
                         //$the_failed_registration_fields[$the_password_repeat_field['reference_id']] = $the_password_repeat_field;
                         $the_failed_registration_fields[$the_email_field['reference_id']] = $the_email_field;
                         $the_failed_registration_fields[$the_email_repeat_field['reference_id']] = $the_email_repeat_field;
                         $the_failed_registration_fields[$the_username_field['reference_id']] = $the_username_field;
                     }
                 }
                 $form_elements_objects = array();
                 $_items = $data->form->getRecord($this->_record_id, $data->published_only, $this->frontend ? $data->own_only_fe ? JFactory::getUser()->get('id', 0) : -1 : ($data->own_only ? JFactory::getUser()->get('id', 0) : -1), $this->frontend ? $data->show_all_languages_fe : true);
                 // asigning the proper names first
                 foreach ($names as $id => $name) {
                     if (!in_array($id, $noneditable_fields)) {
                         $value = '';
                         $is_array = 'STRING';
                         if (is_array(JRequest::getVar('cb_' . $id, ''))) {
                             $is_array = 'ARRAY';
                         }
                         if (isset($the_fields[$id]['options']->allow_raw) && $the_fields[$id]['options']->allow_raw) {
                             $value = JRequest::getVar('cb_' . $id, '', 'POST', $is_array, JREQUEST_ALLOWRAW);
                         } else {
                             if (isset($the_fields[$id]['options']->allow_html) && $the_fields[$id]['options']->allow_html) {
                                 $value = JRequest::getVar('cb_' . $id, '', 'POST', $is_array, JREQUEST_ALLOWHTML);
                             } else {
                                 $value = JRequest::getVar('cb_' . $id, '', 'POST', $is_array);
                             }
                         }
                         if (isset($the_fields[$id]['options']->transfer_format)) {
                             $value = contentbuilder_convert_date($value, $the_fields[$id]['options']->format, $the_fields[$id]['options']->transfer_format);
                         }
                         if (isset($the_html_fields[$id])) {
                             $the_html_fields[$id]['name'] = $name;
                             $the_html_fields[$id]['value'] = $value;
                         } else {
                             if (isset($the_failed_registration_fields[$id])) {
                                 $the_failed_registration_fields[$id]['name'] = $name;
                                 $the_failed_registration_fields[$id]['value'] = $value;
                             } else {
                                 if (isset($the_upload_fields[$id])) {
                                     $the_upload_fields[$id]['name'] = $name;
                                     $the_upload_fields[$id]['value'] = '';
                                     $the_upload_fields[$id]['orig_value'] = '';
                                     if ($id == $the_upload_fields[$id]['reference_id']) {
                                         // delete if triggered
                                         if (JRequest::getInt('cb_delete_' . $id, 0) == 1 && isset($the_upload_fields[$id]['validations']) && $the_upload_fields[$id]['validations'] == '') {
                                             if (count($_items)) {
                                                 foreach ($_items as $_item) {
                                                     if ($_item->recElementId == $the_upload_fields[$id]['reference_id']) {
                                                         $_value = $_item->recValue;
                                                         $_files = explode("\n", str_replace("\r", '', $_value));
                                                         foreach ($_files as $_file) {
                                                             if (strpos(strtolower($_file), '{cbsite}') === 0) {
                                                                 $_file = str_replace(array('{cbsite}', '{CBSite}'), array(JPATH_SITE, JPATH_SITE), $_file);
                                                             }
                                                             if (JFile::exists($_file)) {
                                                                 JFile::delete($_file);
                                                             }
                                                             $values[$id] = '';
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                         $file = JRequest::getVar('cb_' . $id, null, 'files', 'array');
                                         if (trim(JFile::makeSafe($file['name'])) != '' && $file['size'] > 0) {
                                             $filename = trim(JFile::makeSafe($file['name']));
                                             $infile = $filename;
                                             $src = $file['tmp_name'];
                                             $dest = '';
                                             $tmp_dest = '';
                                             $tmp_upload_field_dir = '';
                                             $tmp_upload_dir = '';
                                             if (isset($the_upload_fields[$id]['options']) && isset($the_upload_fields[$id]['options']->upload_directory) && $the_upload_fields[$id]['options']->upload_directory != '') {
                                                 $tmp_upload_field_dir = $the_upload_fields[$id]['options']->upload_directory;
                                                 $tmp_dest = $tmp_upload_field_dir;
                                             } else {
                                                 if ($data->upload_directory != '') {
                                                     $tmp_upload_dir = $data->upload_directory;
                                                     $tmp_dest = $tmp_upload_dir;
                                                 }
                                             }
                                             if (isset($the_upload_fields[$id]['options']) && isset($the_upload_fields[$id]['options']->upload_directory) && $the_upload_fields[$id]['options']->upload_directory != '') {
                                                 $dest = str_replace(array('{CBSite}', '{cbsite}'), JPATH_SITE, $the_upload_fields[$id]['options']->upload_directory);
                                             } else {
                                                 if ($data->upload_directory != '') {
                                                     $dest = str_replace(array('{CBSite}', '{cbsite}'), JPATH_SITE, $data->upload_directory);
                                                 }
                                             }
                                             // create dest path by tokens
                                             $dest = $this->createPathByTokens($dest, $names);
                                             $msg = '';
                                             $uploaded = false;
                                             // FILE SIZE TEST
                                             if ($dest != '' && isset($the_upload_fields[$id]['options']) && isset($the_upload_fields[$id]['options']->max_filesize) && $the_upload_fields[$id]['options']->max_filesize > 0) {
                                                 $val = $the_upload_fields[$id]['options']->max_filesize;
                                                 $val = trim($val);
                                                 $last = strtolower($val[strlen($val) - 1]);
                                                 switch ($last) {
                                                     case 'g':
                                                         $val *= 1024;
                                                     case 'm':
                                                         $val *= 1024;
                                                     case 'k':
                                                         $val *= 1024;
                                                 }
                                                 if ($file['size'] > $val) {
                                                     $msg = JText::_('COM_CONTENTBUILDER_FILESIZE_EXCEEDED') . ' ' . $the_upload_fields[$id]['options']->max_filesize . 'b';
                                                 }
                                             }
                                             // FILE EXT TEST
                                             if ($dest != '' && isset($the_upload_fields[$id]['options']) && isset($the_upload_fields[$id]['options']->allowed_file_extensions) && $the_upload_fields[$id]['options']->allowed_file_extensions != '') {
                                                 $allowed = explode(',', str_replace(' ', '', strtolower($the_upload_fields[$id]['options']->allowed_file_extensions)));
                                                 $ext = strtolower(JFile::getExt($filename));
                                                 if (!in_array($ext, $allowed)) {
                                                     $msg = JText::_('COM_CONTENTBUILDER_FILE_EXTENSION_NOT_ALLOWED');
                                                 }
                                             }
                                             // UPLOAD
                                             if ($dest != '' && $msg == '') {
                                                 // limit file's name size
                                                 $ext = strtolower(JFile::getExt($filename));
                                                 $stripped = JFile::stripExt($filename);
                                                 // in some apache configurations unknown file extensions could lead to security risks
                                                 // because it will try to find an executable extensions within the chain of dots. So we simply remove them.
                                                 $filename = str_replace(array(' ', '.'), '_', $stripped) . '.' . $ext;
                                                 $maxnamesize = 100;
                                                 if (function_exists('mb_strlen')) {
                                                     if (mb_strlen($filename) > $maxnamesize) {
                                                         $filename = mb_substr($filename, mb_strlen($filename) - $maxnamesize);
                                                     }
                                                 } else {
                                                     if (strlen($filename) > $maxnamesize) {
                                                         $filename = substr($filename, strlen($filename) - $maxnamesize);
                                                     }
                                                 }
                                                 // take care of existing filenames
                                                 if (JFile::exists($dest . DS . $filename)) {
                                                     $filename = md5(mt_rand(0, mt_getrandmax()) . time()) . '_' . $filename;
                                                 }
                                                 // create pseudo security index.html
                                                 if (!JFile::exists($dest . DS . 'index.html')) {
                                                     JFile::write($dest . DS . 'index.html', $buffer = '');
                                                 }
                                                 if (count($_items)) {
                                                     $files_to_delete = array();
                                                     foreach ($_items as $_item) {
                                                         if ($_item->recElementId == $the_upload_fields[$id]['reference_id']) {
                                                             $_value = $_item->recValue;
                                                             $_files = explode("\n", str_replace("\r", '', $_value));
                                                             foreach ($_files as $_file) {
                                                                 if (strpos(strtolower($_file), '{cbsite}') === 0) {
                                                                     $_file = str_replace(array('{cbsite}', '{CBSite}'), array(JPATH_SITE, JPATH_SITE), $_file);
                                                                 }
                                                                 $files_to_delete[] = $_file;
                                                             }
                                                             break;
                                                         }
                                                     }
                                                     foreach ($files_to_delete as $file_to_delete) {
                                                         if (JFile::exists($file_to_delete)) {
                                                             JFile::delete($file_to_delete);
                                                         }
                                                     }
                                                 }
                                                 // final upload file moving
                                                 $uploaded = JFile::upload($src, $dest . DS . $filename);
                                                 if (!$uploaded) {
                                                     $msg = JText::_('COM_CONTENTBUILDER_UPLOAD_FAILED');
                                                 }
                                             }
                                             if ($dest == '' || $uploaded !== true) {
                                                 JRequest::setVar('cb_submission_failed', 1);
                                                 JFactory::getApplication()->enqueueMessage($msg . ' (' . $infile . ')', 'error');
                                                 $the_upload_fields[$id]['value'] = '';
                                             } else {
                                                 if (strpos(strtolower($tmp_dest), '{cbsite}') === 0) {
                                                     $dest = str_replace(array(JPATH_SITE, JPATH_SITE), array('{cbsite}', '{CBSite}'), $dest);
                                                 }
                                                 $values[$id] = $dest . DS . $filename;
                                                 $the_upload_fields[$id]['value'] = $values[$id];
                                             }
                                             $the_upload_fields[$id]['orig_value'] = JFile::makeSafe($file['name']);
                                         }
                                         if (trim($the_upload_fields[$id]['custom_validation_script'])) {
                                             $msg = self::customValidate(trim($the_upload_fields[$id]['custom_validation_script']), $the_upload_fields[$id], $merged = array_merge($the_upload_fields, $the_fields, $the_html_fields), JRequest::getCmd('record_id', ''), $data->form, isset($values[$id]) ? $values[$id] : '');
                                             $msg = trim($msg);
                                             if (!empty($msg)) {
                                                 JRequest::setVar('cb_submission_failed', 1);
                                                 JFactory::getApplication()->enqueueMessage(trim($msg), 'error');
                                             }
                                         }
                                         $removables = array();
                                         $validations = explode(',', $the_upload_fields[$id]['validations']);
                                         foreach ($validations as $validation) {
                                             $plgs = CBPluginHelper::importPlugin('contentbuilder_validation', $validation);
                                             $removables = array_merge($removables, $plgs);
                                         }
                                         $dispatcher = JDispatcher::getInstance();
                                         $results = $dispatcher->trigger('onValidate', array($the_upload_fields[$id], $merged = array_merge($the_upload_fields, $the_fields, $the_html_fields), JRequest::getCmd('record_id', ''), $data->form, isset($values[$id]) ? $values[$id] : ''));
                                         foreach ($removables as $removable) {
                                             $dispatcher->detach($removable);
                                         }
                                         $all_errors = implode('', $results);
                                         if (!empty($all_errors)) {
                                             if (isset($values[$id]) && JFile::exists($values[$id])) {
                                                 JFile::delete($values[$id]);
                                             }
                                             JRequest::setVar('cb_submission_failed', 1);
                                             foreach ($results as $result) {
                                                 $result = trim($result);
                                                 if (!empty($result)) {
                                                     JFactory::getApplication()->enqueueMessage(trim($result), 'error');
                                                 }
                                             }
                                         }
                                     }
                                 } else {
                                     if (isset($the_fields[$id])) {
                                         $the_fields[$id]['name'] = $name;
                                         $the_fields[$id]['value'] = $value;
                                     }
                                 }
                             }
                         }
                     }
                 }
                 foreach ($names as $id => $name) {
                     if (!in_array($id, $noneditable_fields)) {
                         if (isset($the_upload_fields[$id]) && $id == $the_upload_fields[$id]['reference_id']) {
                             // nothing, done above already
                         } else {
                             $f = null;
                             if (isset($the_html_fields[$id])) {
                                 $value = JRequest::getVar('cb_' . $id, '', 'POST', 'STRING', JREQUEST_ALLOWHTML);
                                 $f = $the_html_fields[$id];
                                 $the_html_fields[$id]['value'] = $value;
                             }
                             if (isset($the_failed_registration_fields[$id])) {
                                 $value = JRequest::getVar('cb_' . $id, '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW);
                                 $f = $the_failed_registration_fields[$id];
                                 $the_failed_registration_fields[$id]['value'] = $value;
                             }
                             if (isset($the_fields[$id])) {
                                 $is_array = 'STRING';
                                 if (is_array(JRequest::getVar('cb_' . $id, ''))) {
                                     $is_array = 'ARRAY';
                                 }
                                 if (isset($the_fields[$id]['options']->allow_raw) && $the_fields[$id]['options']->allow_raw) {
                                     $value = JRequest::getVar('cb_' . $id, '', 'POST', $is_array, JREQUEST_ALLOWRAW);
                                 } else {
                                     if (isset($the_fields[$id]['options']->allow_html) && $the_fields[$id]['options']->allow_html) {
                                         $value = JRequest::getVar('cb_' . $id, '', 'POST', $is_array, JREQUEST_ALLOWHTML);
                                     } else {
                                         $value = JRequest::getVar('cb_' . $id, '', 'POST', $is_array);
                                     }
                                 }
                                 if (isset($the_fields[$id]['options']->transfer_format)) {
                                     $value = contentbuilder_convert_date($value, $the_fields[$id]['options']->format, $the_fields[$id]['options']->transfer_format);
                                 }
                                 $f = $the_fields[$id];
                                 $the_fields[$id]['value'] = $value;
                             }
                             if ($f !== null) {
                                 if (trim($f['custom_validation_script'])) {
                                     $msg = self::customValidate(trim($f['custom_validation_script']), $f, $merged = array_merge($the_upload_fields, $the_fields, $the_html_fields), JRequest::getCmd('record_id', ''), $data->form, $value);
                                     $msg = trim($msg);
                                     if (!empty($msg)) {
                                         JRequest::setVar('cb_submission_failed', 1);
                                         JFactory::getApplication()->enqueueMessage(trim($msg), 'error');
                                     }
                                 }
                                 $removables = array();
                                 $validations = explode(',', $f['validations']);
                                 foreach ($validations as $validation) {
                                     $plgs = CBPluginHelper::importPlugin('contentbuilder_validation', $validation);
                                     $removables = array_merge($removables, $plgs);
                                 }
                                 $dispatcher = JDispatcher::getInstance();
                                 $results = $dispatcher->trigger('onValidate', array($f, $merged = array_merge($the_upload_fields, $the_fields, $the_html_fields), JRequest::getCmd('record_id', ''), $data->form, $value));
                                 foreach ($removables as $removable) {
                                     $dispatcher->detach($removable);
                                 }
                                 $all_errors = implode('', $results);
                                 $values[$id] = $value;
                                 if (!empty($all_errors)) {
                                     JRequest::setVar('cb_submission_failed', 1);
                                     foreach ($results as $result) {
                                         $result = trim($result);
                                         if (!empty($result)) {
                                             JFactory::getApplication()->enqueueMessage(trim($result), 'error');
                                         }
                                     }
                                 } else {
                                     $removables = array();
                                     $plgs = CBPluginHelper::importPlugin('contentbuilder_form_elements', $f['type']);
                                     $removables = array_merge($removables, $plgs);
                                     $dispatcher = JDispatcher::getInstance();
                                     $plugin_validations = $dispatcher->trigger('onAfterValidationSuccess', array($f, $m = array_merge($the_upload_fields, $the_fields, $the_html_fields), JRequest::getCmd('record_id', ''), $data->form, $value));
                                     if (count($plugin_validations)) {
                                         $form_elements_objects[] = $plugin_validations[0];
                                     }
                                     foreach ($removables as $removable) {
                                         $dispatcher->detach($removable);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 $submit_before_result = $submit_dispatcher->trigger('onBeforeSubmit', array(JRequest::getCmd('record_id', ''), $data->form, $values));
                 if (JRequest::getVar('cb_submission_failed', 0)) {
                     JFactory::getSession()->set('cb_failed_values', $values, 'com_contentbuilder.' . $this->_id);
                     return JRequest::getCmd('record_id', '');
                 }
                 $record_return = $data->form->saveRecord(JRequest::getCmd('record_id', ''), $values);
                 foreach ($form_elements_objects as $form_elements_object) {
                     if ($form_elements_object instanceof CBFormElementAfterValidation) {
                         $form_elements_object->onSaveRecord($record_return);
                     }
                 }
                 if ($data->act_as_registration && $record_return) {
                     $meta = $data->form->getRecordMetadata($record_return);
                     if (!$data->registration_bypass_plugin || $meta->created_id) {
                         $user_id = $this->register('', '', '', $meta->created_id, JRequest::getVar('cb_' . $the_name_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_username_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_email_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_password_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW));
                         if (intval($user_id) > 0) {
                             JFactory::getSession()->set('cb_last_record_user_id', $user_id, 'com_contentbuilder');
                             $data->form->saveRecordUserData($record_return, $user_id, JRequest::getVar('cb_' . $the_name_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_username_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW));
                         }
                     } else {
                         if (!$meta->created_id) {
                             $bypass = new stdClass();
                             $verification_name = str_replace(array(';', '___', '|'), '-', trim($data->registration_bypass_verification_name) ? trim($data->registration_bypass_verification_name) : $data->title);
                             $verify_view = trim($data->registration_bypass_verify_view) ? trim($data->registration_bypass_verify_view) : $data->id;
                             $bypass->text = $orig_text = '{CBVerify plugin: ' . $data->registration_bypass_plugin . '; verification-name: ' . $verification_name . '; verify-view: ' . $verify_view . '; ' . str_replace(array("\r", "\n"), '', $data->registration_bypass_plugin_params) . '}';
                             $params = new stdClass();
                             JPluginHelper::importPlugin('content', 'contentbuilder_verify');
                             $bypass_dispatcher = JDispatcher::getInstance();
                             $bypass_result = $bypass_dispatcher->trigger('onPrepareContent', array(&$bypass, &$params));
                             $verification_id = '';
                             if ($bypass->text != $orig_text) {
                                 $verification_id = md5(uniqid(null, true) . mt_rand(0, mt_getrandmax()) . JFactory::getUser()->get('id', 0));
                             }
                             $user_id = $this->register($data->registration_bypass_plugin, $verification_name, $verification_id, $meta->created_id, JRequest::getVar('cb_' . $the_name_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_username_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_email_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_password_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW));
                             if (intval($user_id) > 0) {
                                 JFactory::getSession()->set('cb_last_record_user_id', $user_id, 'com_contentbuilder');
                                 $data->form->saveRecordUserData($record_return, $user_id, JRequest::getVar('cb_' . $the_name_field['reference_id'], '', 'POST', 'STRING', JREQUEST_ALLOWRAW), JRequest::getVar('cb_' . $the_username_field['reference_id'], '', 'POST', 'STRING', JREQUEST_NOTRIM | JREQUEST_ALLOWRAW));
                             }
                             if ($bypass->text != $orig_text && intval($user_id) > 0) {
                                 $_now = JFactory::getDate();
                                 $setup = JFactory::getSession()->get($data->registration_bypass_plugin . $verification_name, '', 'com_contentbuilder.verify.' . $data->registration_bypass_plugin . $verification_name);
                                 JFactory::getSession()->clear($data->registration_bypass_plugin . $verification_name, 'com_contentbuilder.verify.' . $data->registration_bypass_plugin . $verification_name);
                                 jimport('joomla.version');
                                 $version = new JVersion();
                                 if (version_compare($version->getShortVersion(), '3.0', '>=')) {
                                     $___now = $_now->toSql();
                                 } else {
                                     $___now = $_now->toMySQL();
                                 }
                                 $this->_db->setQuery("\n                                            Insert Into #__contentbuilder_verifications\n                                            (\n                                            `verification_hash`,\n                                            `start_date`,\n                                            `verification_data`,\n                                            `user_id`,\n                                            `plugin`,\n                                            `ip`,\n                                            `setup`,\n                                            `client`\n                                            )\n                                            Values\n                                            (\n                                            " . $this->_db->Quote($verification_id) . ",\n                                            " . $this->_db->Quote($___now) . ",\n                                            " . $this->_db->Quote('type=registration&') . ",\n                                            " . $user_id . ",\n                                            " . $this->_db->Quote($data->registration_bypass_plugin) . ",\n                                            " . $this->_db->Quote($_SERVER['REMOTE_ADDR']) . ",\n                                            " . $this->_db->Quote($setup) . ",\n                                            " . intval(JFactory::getApplication()->isAdmin() ? 1 : 0) . "\n                                            )\n                                    ");
                                 $this->_db->query();
                             }
                         }
                     }
                 }
                 if ($this->frontend && !JRequest::getCmd('record_id', '') && $record_return && !JRequest::getVar('return', '')) {
                     if ($data->force_login) {
                         if (!JFactory::getUser()->get('id', 0)) {
                             if (!$this->is15) {
                                 JRequest::setVar('return', base64_encode(JRoute::_('index.php?option=com_users&view=login&Itemid=' . JRequest::getInt('Itemid', 0), false)));
                             } else {
                                 JRequest::setVar('return', base64_encode(JRoute::_('index.php?option=com_user&view=login&Itemid=' . JRequest::getInt('Itemid', 0), false)));
                             }
                         } else {
                             if (!$this->is15) {
                                 JRequest::setVar('return', base64_encode(JRoute::_('index.php?option=com_users&view=profile&Itemid=' . JRequest::getInt('Itemid', 0), false)));
                             } else {
                                 JRequest::setVar('return', base64_encode(JRoute::_('index.php?option=com_user&view=user&Itemid=' . JRequest::getInt('Itemid', 0), false)));
                             }
                         }
                     } else {
                         if (trim($data->force_url)) {
                             JRequest::setVar('cbInternalCheck', 0);
                             JRequest::setVar('return', base64_encode(trim($data->force_url)));
                         }
                     }
                 }
                 if ($record_return) {
                     $sef = '';
                     $ignore_lang_code = '*';
                     if ($data->default_lang_code_ignore) {
                         jimport('joomla.version');
                         $version = new JVersion();
                         if (version_compare($version->getShortVersion(), '1.6', '>=')) {
                             $this->_db->setQuery("Select lang_code From #__languages Where published = 1 And sef = " . $this->_db->Quote(trim(JRequest::getCmd('lang', ''))));
                             $ignore_lang_code = $this->_db->loadResult();
                             if (!$ignore_lang_code) {
                                 $ignore_lang_code = '*';
                             }
                         } else {
                             $codes = contentbuilder::getLanguageCodes();
                             foreach ($codes as $code) {
                                 if (strstr(strtolower($code), strtolower(trim(JRequest::getCmd('lang', '')))) !== false) {
                                     $ignore_lang_code = strtolower($code);
                                     break;
                                 }
                             }
                         }
                         $sef = trim(JRequest::getCmd('lang', ''));
                         if ($ignore_lang_code == '*') {
                             $sef = '';
                         }
                     } else {
                         jimport('joomla.version');
                         $version = new JVersion();
                         if (version_compare($version->getShortVersion(), '1.6', '>=')) {
                             $this->_db->setQuery("Select sef From #__languages Where published = 1 And lang_code = " . $this->_db->Quote($data->default_lang_code));
                             $sef = $this->_db->loadResult();
                         } else {
                             $codes = contentbuilder::getLanguageCodes();
                             foreach ($codes as $code) {
                                 if ($code == $data->default_lang_code) {
                                     $sef = explode('-', $code);
                                     if (count($sef)) {
                                         $sef = strtolower($sef[0]);
                                     }
                                     break;
                                 }
                             }
                         }
                     }
                     $language = $data->default_lang_code_ignore ? $ignore_lang_code : $data->default_lang_code;
                     $this->_db->setQuery("Select id, edited From #__contentbuilder_records Where `type` = " . $this->_db->Quote($data->type) . " And `reference_id` = " . $this->_db->Quote($data->form->getReferenceId()) . " And record_id = " . $this->_db->Quote($record_return));
                     $res = $this->_db->loadAssoc();
                     $last_update = JFactory::getDate();
                     jimport('joomla.version');
                     $version = new JVersion();
                     if (version_compare($version->getShortVersion(), '3.0', '>=')) {
                         $last_update = $last_update->toSql();
                     } else {
                         $last_update = $last_update->toMySQL();
                     }
                     if (!is_array($res)) {
                         $is_future = 0;
                         $created_up = JFactory::getDate();
                         if (version_compare($version->getShortVersion(), '3.0', '>=')) {
                             $created_up = $created_up->toSql();
                         } else {
                             $created_up = $created_up->toMySQL();
                         }
                         if (intval($data->default_publish_up_days) != 0) {
                             $is_future = 1;
                             $date = JFactory::getDate(strtotime('now +' . intval($data->default_publish_up_days) . ' days'));
                             if (version_compare($version->getShortVersion(), '3.0', '>=')) {
                                 $created_up = $date->toSql();
                             } else {
                                 $created_up = $date->toMySQL();
                             }
                         }
                         $created_down = '0000-00-00 00:00:00';
                         if (intval($data->default_publish_down_days) != 0) {
                             $date = JFactory::getDate(strtotime($created_up . ' +' . intval($data->default_publish_down_days) . ' days'));
                             if (version_compare($version->getShortVersion(), '3.0', '>=')) {
                                 $created_down = $date->toSql();
                             } else {
                                 $created_down = $date->toMySQL();
                             }
                         }
                         $this->_db->setQuery("Insert Into #__contentbuilder_records (session_id,`type`,last_update,is_future,lang_code, sef, published, record_id, reference_id, publish_up, publish_down) Values ('" . JFactory::getSession()->getId() . "'," . $this->_db->Quote($data->type) . "," . $this->_db->Quote($last_update) . ",{$is_future}," . $this->_db->Quote($language) . "," . $this->_db->Quote(trim($sef)) . "," . $this->_db->Quote($data->auto_publish && !$is_future ? 1 : 0) . ", " . $this->_db->Quote($record_return) . ", " . $this->_db->Quote($data->form->getReferenceId()) . ", " . $this->_db->Quote($created_up) . ", " . $this->_db->Quote($created_down) . ")");
                         $this->_db->query();
                     } else {
                         $this->_db->setQuery("Update #__contentbuilder_records Set last_update = " . $this->_db->Quote($last_update) . ",lang_code = " . $this->_db->Quote($language) . ", sef = " . $this->_db->Quote(trim($sef)) . ", edited = edited + 1 Where `type` = " . $this->_db->Quote($data->type) . " And  `reference_id` = " . $this->_db->Quote($data->form->getReferenceId()) . " And record_id = " . $this->_db->Quote($record_return));
                         $this->_db->query();
                     }
                 }
             } else {
                 $record_return = JRequest::getCmd('record_id', '');
             }
             $data->items = $data->form->getRecord($record_return, $data->published_only, $this->frontend ? $data->own_only_fe ? JFactory::getUser()->get('id', 0) : -1 : ($data->own_only ? JFactory::getUser()->get('id', 0) : -1), true);
             $data_email_items = $data->form->getRecord($record_return, false, -1, false);
             $data->labels = $data->form->getElementLabels();
             $ids = array();
             foreach ($data->labels as $reference_id => $label) {
                 $ids[] = $this->_db->Quote($reference_id);
             }
             $data->labels = array();
             if (count($ids)) {
                 $this->_db->setQuery("Select Distinct `label`, reference_id From #__contentbuilder_elements Where form_id = " . intval($this->_id) . " And reference_id In (" . implode(',', $ids) . ") And published = 1 Order By ordering");
                 $rows = $this->_db->loadAssocList();
                 $ids = array();
                 foreach ($rows as $row) {
                     $ids[] = $row['reference_id'];
                 }
             }
             $article_id = 0;
             // creating the article
             if ($data->create_articles && count($data->items)) {
                 $data->page_title = $data->use_view_name_as_title ? $data->name : $data->form->getPageTitle();
                 //if(!count($data->items)){
                 //     JError::raiseError(404, JText::_('COM_CONTENTBUILDER_RECORD_NOT_FOUND'));
                 //}
                 $this->_db->setQuery("Select articles.`id` From #__contentbuilder_articles As articles, #__content As content Where content.id = articles.article_id And (content.state = 1 Or content.state = 0) And articles.form_id = " . intval($this->_id) . " And articles.record_id = " . $this->_db->Quote($record_return));
                 $article = $this->_db->loadResult();
                 $config = array();
                 if ($article) {
                     if (!$this->is15) {
                         $config = JRequest::getVar('jform', array());
                     } else {
                         $config = array('ordering' => JRequest::getInt('ordering', 0), 'sectionid' => JRequest::getInt('sectionid', 0), 'catid' => JRequest::getInt('catid', 0), 'alias' => JRequest::getVar('alias', ''), 'frontpage' => JRequest::getInt('frontpage', 0), 'state' => JRequest::getInt('state', 0), 'details' => JRequest::getVar('details', array()), 'params' => JRequest::getVar('params', array()), 'meta' => JRequest::getVar('meta', array()));
                     }
                 }
                 $full = $this->frontend ? contentbuilder::authorizeFe('fullarticle') : contentbuilder::authorize('fullarticle');
                 $article_id = contentbuilder::createArticle($this->_id, $record_return, $data->items, $ids, $data->title_field, $data->form->getRecordMetadata($record_return), $config, $full, $this->frontend ? $data->limited_article_options_fe : $data->limited_article_options, JRequest::getVar('cb_category_id', null));
                 if (isset($form_elements_objects)) {
                     foreach ($form_elements_objects as $form_elements_object) {
                         if ($form_elements_object instanceof CBFormElementAfterValidation) {
                             $form_elements_object->onSaveArticle($article_id);
                         }
                     }
                 }
             }
             // required to determine blocked users in system plugin
             if ($data->act_as_registration && isset($user_id) && intval($user_id) > 0) {
                 $this->_db->setQuery("Insert Into #__contentbuilder_registered_users (user_id, form_id, record_id) Values (" . intval($user_id) . ", " . $this->_id . ", " . $this->_db->Quote($record_return) . ")");
                 $this->_db->query();
             }
             if (!$data->edit_by_type) {
                 $cleanedValues = array();
                 foreach ($values as $rawvalue) {
                     if (is_array($rawvalue)) {
                         if (isset($rawvalue[0]) && $rawvalue[0] == 'cbGroupMark') {
                             unset($rawvalue[0]);
                             $cleanedValues[] = array_values($rawvalue);
                         } else {
                             $cleanedValues[] = $rawvalue;
                         }
                     } else {
                         $cleanedValues[] = $rawvalue;
                     }
                 }
                 $submit_after_result = $submit_dispatcher->trigger('onAfterSubmit', array($record_return, $article_id, $data->form, $cleanedValues));
                 foreach ($fields as $actionField) {
                     if (trim($actionField['custom_action_script'])) {
                         self::customAction(trim($actionField['custom_action_script']), $record_return, $article_id, $data->form, $actionField, $fields, $cleanedValues);
                     }
                 }
                 if (!JRequest::getCmd('record_id', '') && $data->email_notifications || JRequest::getCmd('record_id', '') && $data->email_update_notifications) {
                     $from = $MailFrom = CBCompat::getJoomlaConfig('config.mailfrom');
                     $fromname = CBCompat::getJoomlaConfig('config.fromname');
                     $mailer = JFactory::getMailer();
                     $email_admin_template = '';
                     $email_template = '';
                     // admin email
                     if (trim($data->email_admin_recipients)) {
                         // sender
                         if (trim($data->email_admin_alternative_from)) {
                             foreach ($data->items as $item) {
                                 $data->email_admin_alternative_from = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_admin_alternative_from);
                             }
                             $from = $data->email_admin_alternative_from;
                         }
                         if (trim($data->email_admin_alternative_fromname)) {
                             foreach ($data->items as $item) {
                                 $data->email_admin_alternative_fromname = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_admin_alternative_fromname);
                             }
                             $fromname = $data->email_admin_alternative_fromname;
                         }
                         $mailer->setSender(array(trim($MailFrom), trim($fromname)));
                         $mailer->addReplyTo(array($from, $fromname));
                         // recipients
                         foreach ($data->items as $item) {
                             $data->email_admin_recipients = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_admin_recipients);
                         }
                         $recipients_checked_admin = array();
                         $recipients_admin = explode(';', $data->email_admin_recipients);
                         foreach ($recipients_admin as $recipient_admin) {
                             if (contentbuilder_is_email(trim($recipient_admin))) {
                                 $recipients_checked_admin[] = trim($recipient_admin);
                             }
                         }
                         $mailer->addBCC($recipients_checked_admin);
                         $email_admin_template = contentbuilder::getEmailTemplate($this->_id, $record_return, $data_email_items, $ids, true);
                         // subject
                         $subject_admin = JText::_('COM_CONTENTBUILDER_EMAIL_RECORD_RECEIVED');
                         if (trim($data->email_admin_subject)) {
                             foreach ($data->items as $item) {
                                 $data->email_admin_subject = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_admin_subject);
                             }
                             $subject_admin = $data->email_admin_subject;
                             $subject_admin = str_replace(array('{RECORD_ID}', '{record_id}'), $record_return, $subject_admin);
                             $subject_admin = str_replace(array('{USER_ID}', '{user_id}'), JFactory::getUser()->get('id'), $subject_admin);
                             $subject_admin = str_replace(array('{USERNAME}', '{username}'), JFactory::getUser()->get('username'), $subject_admin);
                             $subject_admin = str_replace(array('{USER_FULL_NAME}', '{user_full_name}'), JFactory::getUser()->get('name'), $subject_admin);
                             $subject_admin = str_replace(array('{EMAIL}', '{email}'), JFactory::getUser()->get('email'), $subject_admin);
                             $subject_admin = str_replace(array('{VIEW_NAME}', '{view_name}'), $data->name, $subject_admin);
                             $subject_admin = str_replace(array('{VIEW_ID}', '{view_id}'), $this->_id, $subject_admin);
                             $subject_admin = str_replace(array('{IP}', '{ip}'), $_SERVER['REMOTE_ADDR'], $subject_admin);
                         }
                         $mailer->setSubject($subject_admin);
                         // attachments
                         foreach ($data->items as $item) {
                             $data->email_admin_recipients_attach_uploads = str_replace('{' . $item->recName . '}', $item->recValue, $data->email_admin_recipients_attach_uploads);
                         }
                         $attachments_admin = explode(';', $data->email_admin_recipients_attach_uploads);
                         $attached_admin = array();
                         foreach ($attachments_admin as $attachment_admin) {
                             $attachment_admin = explode("\n", str_replace("\r", "", trim($attachment_admin)));
                             foreach ($attachment_admin as $att_admin) {
                                 if (strpos(strtolower($att_admin), '{cbsite}') === 0) {
                                     $att_admin = str_replace(array('{cbsite}', '{CBSite}'), array(JPATH_SITE, JPATH_SITE), $att_admin);
                                 }
                                 if (JFile::exists(trim($att_admin))) {
                                     $attached_admin[] = trim($att_admin);
                                 }
                             }
                         }
                         $mailer->addAttachment($attached_admin);
                         $mailer->isHTML($data->email_admin_html);
                         $mailer->setBody($email_admin_template);
                         if (count($recipients_checked_admin)) {
                             $send = $mailer->Send();
                             if ($send !== true) {
                                 JFactory::getApplication()->enqueueMessage('Error sending email: ' . $mailer->ErrorInfo, 'error');
                             }
                         }
                         $mailer->ClearAddresses();
                         $mailer->ClearAllRecipients();
                         $mailer->ClearAttachments();
                     }
                     // public email
                     if (trim($data->email_recipients)) {
                         // sender
                         if (trim($data->email_alternative_from)) {
                             foreach ($data->items as $item) {
                                 $data->email_alternative_from = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_alternative_from);
                             }
                             $from = $data->email_alternative_from;
                         }
                         if (trim($data->email_alternative_fromname)) {
                             foreach ($data->items as $item) {
                                 $data->email_alternative_fromname = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_alternative_fromname);
                             }
                             $fromname = $data->email_alternative_fromname;
                         }
                         $mailer->setSender(array(trim($MailFrom), trim($fromname)));
                         $mailer->addReplyTo(array($from, $fromname));
                         // recipients
                         foreach ($data->items as $item) {
                             $data->email_recipients = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_recipients);
                         }
                         $recipients_checked = array();
                         $recipients = explode(';', $data->email_recipients);
                         foreach ($recipients as $recipient) {
                             if (contentbuilder_is_email($recipient)) {
                                 $recipients_checked[] = $recipient;
                             }
                         }
                         $mailer->addBCC($recipients_checked);
                         $email_template = contentbuilder::getEmailTemplate($this->_id, $record_return, $data_email_items, $ids, false);
                         // subject
                         $subject = JText::_('COM_CONTENTBUILDER_EMAIL_RECORD_RECEIVED');
                         if (trim($data->email_subject)) {
                             foreach ($data->items as $item) {
                                 $data->email_subject = str_replace('{' . $item->recName . '}', cbinternal($item->recValue), $data->email_subject);
                             }
                             $subject = $data->email_subject;
                             $subject = str_replace(array('{RECORD_ID}', '{record_id}'), $record_return, $subject);
                             $subject = str_replace(array('{USER_ID}', '{user_id}'), JFactory::getUser()->get('id'), $subject);
                             $subject = str_replace(array('{USERNAME}', '{username}'), JFactory::getUser()->get('username'), $subject);
                             $subject = str_replace(array('{EMAIL}', '{email}'), JFactory::getUser()->get('email'), $subject);
                             $subject = str_replace(array('{USER_FULL_NAME}', '{user_full_name}'), JFactory::getUser()->get('name'), $subject);
                             $subject = str_replace(array('{VIEW_NAME}', '{view_name}'), $data->name, $subject);
                             $subject = str_replace(array('{VIEW_ID}', '{view_id}'), $this->_id, $subject);
                             $subject = str_replace(array('{IP}', '{ip}'), $_SERVER['REMOTE_ADDR'], $subject);
                         }
                         $mailer->setSubject($subject);
                         // attachments
                         foreach ($data->items as $item) {
                             $data->email_recipients_attach_uploads = str_replace('{' . $item->recName . '}', $item->recValue, $data->email_recipients_attach_uploads);
                         }
                         $attachments = explode(';', $data->email_recipients_attach_uploads);
                         $attached = array();
                         foreach ($attachments as $attachment) {
                             $attachment = explode("\n", str_replace("\r", "", trim($attachment)));
                             foreach ($attachment as $att) {
                                 if (strpos(strtolower($att), '{cbsite}') === 0) {
                                     $att = str_replace(array('{cbsite}', '{CBSite}'), array(JPATH_SITE, JPATH_SITE), $att);
                                 }
                                 if (JFile::exists(trim($att))) {
                                     $attached[] = trim($att);
                                 }
                             }
                         }
                         $mailer->addAttachment($attached);
                         $mailer->isHTML($data->email_html);
                         $mailer->setBody($email_template);
                         if (count($recipients_checked)) {
                             $send = $mailer->Send();
                             if ($send !== true) {
                                 JFactory::getApplication()->enqueueMessage('Error sending email: ' . $mailer->ErrorInfo, 'error');
                             }
                         }
                         $mailer->ClearAddresses();
                         $mailer->ClearAllRecipients();
                         $mailer->ClearAttachments();
                     }
                 }
             }
             return $record_return;
         }
     }
     if (!$this->is15) {
         $cache = JFactory::getCache('com_content');
         $cache->clean();
         $cache = JFactory::getCache('com_contentbuilder');
         $cache->clean();
     } else {
         $cache = JFactory::getCache('com_content');
         $cache->clean();
         $cache = JFactory::getCache('com_contentbuilder');
         $cache->clean();
     }
     return false;
 }