/**
  * HOW IT WORKS
  * 1 - If the idContent is set retrieve all the fields and values for this ID, otherwise retrieve only the fields to show
  * 2 - On save check the errors on the "normal fields"; for the attachments save everything into the tmp folder and check for errors
  * 3 - If there aren't errors save the content (insert or update), save the values and moving the attachments from the tmp folder to the content folder
  * 4 - Process the images, if any
  * 5 - Empty the TMP folder
  * 6 - Redirect to the result page
  *
  */
 public function saveContent($contentType, $content = null)
 {
     $result = array();
     $uploadData = array();
     $redirectURL = '/admin/contents/';
     $oldValues = array();
     $errors = array();
     $result['data_saved'] = FALSE;
     $contentTypeName = $contentType;
     $contentType = $this->getContentTypeByName($contentType);
     $fields = $this->getContentFieldsByIdContentType($contentType['id']);
     $categories = $this->getCategoriesByContentType($contentType['id']);
     $oldValues['title'] = '';
     $oldValues['relative_path'] = '';
     $absolutePath = '';
     $oldValues['categories'] = array();
     if ($content) {
         $idContent = $content['id'];
     } else {
         $idContent = null;
     }
     if ($contentTypeName === 'pages') {
         $menu = $this->getMenu(true);
         $flatPagesTree = $this->getFlatPagesTree($menu);
         $flatPagesTitles = array();
         foreach ($flatPagesTree as $id => $page) {
             $flatPagesTitles[$id] = ltrim(str_repeat('--', $page['level']) . ' ', ' ') . "{$page['title']}";
         }
         // TODO another day
         // if ($idContent && isset($flatPagesTitles[$idContent])) {
         // 	unset($flatPagesTitles[$idContent]);
         // }
     }
     // ================ 1 - RETRIEVING ALL THE CONTENT COMPONENTS (FIELDS, VALUES, ATTACHS, ETC.) ===============
     // Retrieve the content if the idContent is set
     if ($idContent) {
         $this->data['uploadUrl'] = '/uploads/' . $idContent . '/';
         $content = $this->getContentById($idContent);
         $contentValues = $this->getAllContentValuesByIdContent($idContent);
         $contentCategories = $this->getAllContentCategoriesByIdContent($idContent);
         $oldValues['title'] = $content['title'];
         $oldValues['relative_path'] = $content['relative_path'];
         $oldValues['categories'] = $contentCategories;
         if (count($oldValues['categories']) > 0) {
             $tmp = array();
             foreach ($oldValues['categories'] as $category) {
                 $tmp[] = $category['id_category'];
             }
             $oldValues['categories'] = $tmp;
         }
         $tmp = array();
         if (count($contentValues) > 0) {
             foreach ($contentValues as $value) {
                 $tmp[$value['id_content_field']] = $value;
             }
         }
         $contentValues = $tmp;
     } else {
         $content = array();
         $contentValues = array();
         $contentCategories = array();
     }
     $contentAttachments = array();
     // Fields transformations (options, images, etc.)
     if (count($fields) > 0) {
         foreach ($fields as $index => $field) {
             if (isset($contentValues[$field['id']]['value']) && $contentValues[$field['id']]['value'] != '') {
                 $field['value'] = $contentValues[$field['id']]['value'];
             } else {
                 $field['value'] = '';
             }
             if (in_array($field['type'], array('radio', 'select', 'multiselect', 'checkbox', 'multicheckbox'))) {
                 $field['options'] = FM_Utility::convertOptionsTextToArray($field['options']);
             }
             if (in_array($field['type'], array('multiselect', 'multicheckbox', 'multiple_linked_content')) && $field['value'] != '') {
                 $field['value'] = FM_Utility::convertMultiOptionsTextToArray($contentValues[$field['id']]['value']);
             }
             if ($field['type'] == 'file_upload') {
                 if (isset($contentValues[$field['id']])) {
                     $field['attach'] = array('id_content_value' => $contentValues[$field['id']]['id'], 'file' => $this->data['uploadUrl'] . $contentValues[$field['id']]['value']);
                 } else {
                     $field['attach'] = array();
                 }
             }
             if ($field['type'] == 'image_upload') {
                 if (isset($contentValues[$field['id']])) {
                     $field['attach'] = array('id_content_value' => $contentValues[$field['id']]['id'], 'zoom_image' => $this->data['uploadUrl'] . $contentValues[$field['id']]['value'], 'thumb_image' => $this->data['uploadUrl'] . 'thumbs/' . $contentValues[$field['id']]['value']);
                 } else {
                     $field['attach'] = array();
                 }
             }
             if ($field['type'] == 'gallery') {
                 $contentAttachments[$field['name']] = $this->getAllContentAttachmentsByIdContent($idContent);
                 $field['attachs'] = array();
                 if (count($contentAttachments[$field['name']]) > 0) {
                     foreach ($contentAttachments[$field['name']] as $att) {
                         array_push($field['attachs'], array('id_content_attachment' => $att['id'], 'zoom_image' => $this->data['uploadUrl'] . $att['filename'], 'thumb_image' => $this->data['uploadUrl'] . 'thumbs/' . $att['filename']));
                     }
                 }
             }
             if ($field['type'] == 'linked_content' || $field['type'] == 'multiple_linked_content') {
                 $ctypeToSelect = $this->getContentTypeById($field['linked_id_content_type']);
                 $contentSearch = new FM_ContentSearch();
                 $contentSearch->initialize($ctypeToSelect['content_type'])->select('*')->fullInfo(TRUE);
                 $contentList = $contentSearch->getContentList();
                 $options = array();
                 foreach ($contentList as $cont) {
                     $options[$cont['id']] = $cont['title'];
                 }
                 $field['options'] = $options;
             }
             if ($field['name'] === 'parent_page_id' && $contentTypeName === 'pages' && $field['type'] == 'select') {
                 $field['options'] = $flatPagesTitles;
             }
             // PAGE FIELD MANAGEMENT
             if ($field['name'] == 'content_types_list' && $contentTypeName == 'pages' && $field['type'] == 'select') {
                 $cTypes = $this->getContentTypes('pages');
                 $options = array();
                 if (count($cTypes) > 0) {
                     foreach ($cTypes as $ct) {
                         $options[$ct['content_type']] = $ct['content_type'];
                     }
                 }
                 $field['options'] = $options;
                 // If the value exist, I load the options for the content list
                 if ($field['value'] != '') {
                     $contentListOptions = array();
                     $contentSearch = new FM_ContentSearch();
                     $contentSearch->initialize($field['value'])->select('*')->fullInfo(TRUE);
                     $tmpContentList = $contentSearch->getContentList();
                     if (count($tmpContentList) > 0) {
                         foreach ($tmpContentList as $tmpContent) {
                             $contentListOptions[$tmpContent['id']] = $tmpContent['title'];
                         }
                     }
                 }
             }
             if ($field['name'] === 'content_list_categories' && $contentTypeName === 'pages' && in_array($field['type'], array('multiselect', 'multicheckbox'))) {
                 $field['options'] = (array) $field['value'];
                 $field['options'] = array_combine($field['options'], $field['options']);
             }
             if ($field['name'] == 'content_list' && $contentTypeName == 'pages' && ($field['type'] == 'select' || $field['type'] == 'multiselect')) {
                 // Check if the operation value exist
                 if (isset($contentListOptions) && count($contentListOptions) > 0) {
                     $field['options'] = $contentListOptions;
                 }
             }
             $fields[$index] = $field;
         }
     }
     if ($this->ci->input->post('save') || $this->ci->input->post('save_list')) {
         $redirectURL .= $this->ci->input->post('save') ? 'edit/' : 'index/' . $contentType['content_type'];
         $tmpFolder = $this->getTmpFolder();
         // Generic saving of the values
         foreach ($this->ci->input->post() as $name => $value) {
             $oldValues[$name] = $value;
         }
         if (count($fields) > 0) {
             foreach ($fields as $index => $field) {
                 if ($this->ci->input->post($field['name'])) {
                     $field['value'] = $this->ci->input->post($field['name']);
                 }
                 $fields[$index] = $field;
             }
         }
         // Basic content checking
         if ($this->ci->input->post('title') == '') {
             $errors['title'] = $this->ci->lang->line('incorrect_content_title');
         }
         if ($this->ci->input->post('relative_path') == '') {
             $errors['relative_path'] = sprintf($this->ci->lang->line('incorrect_field'), 'relative path');
         } else {
             $_POST['relative_path'] = $relativePath = url_title(convert_accented_characters($this->ci->input->post('relative_path')), '-', true);
         }
         // Check for page absolute_path uniqueness
         if ($contentTypeName === 'pages' && !isset($errors['relative_path']) && isset($flatPagesTitles)) {
             $absolutePath = "{$relativePath}/";
             $parentPageId = $this->ci->input->post('parent_page_id');
             if ($parentPageId) {
                 $absolutePath = "{$flatPagesTree[$parentPageId]['absolute_path']}{$absolutePath}";
             }
             $contentSearch = new FM_ContentSearch();
             $contentSearch->initialize($contentType['id'])->select('id')->addWhereCondition('absolute_path', '=', $absolutePath)->addWhereCondition('lang', '=', $this->ci->input->post('lang'));
             $content = current($contentSearch->getContentList());
             if ($content && (!$idContent || $content['id'] !== $idContent)) {
                 $errors['relative_path'] = $this->ci->lang->line('non_unique_absolute_path');
             }
         } else {
             $absolutePath = url_title(convert_accented_characters($oldValues['title']));
         }
         // ================ 2 - CHECKING THE ERRORS ========================
         if (count($fields) > 0) {
             foreach ($fields as $index => $field) {
                 if (!$this->isFilesystemField($field)) {
                     if ($field['mandatory'] == TRUE && $this->ci->input->post($field['name']) == '') {
                         $field['showError'] = TRUE;
                         $field['error'] = sprintf($this->ci->lang->line('incorrect_field'), $field['label']);
                     }
                     if ($field['type'] == 'date' || $field['type'] == 'datetime') {
                         $value = $this->ci->input->post($field['name']);
                         if ($value) {
                             $field['value'] = $value;
                             if ($field['type'] == 'datetime') {
                                 list($date, $time) = explode(' ', $value);
                             } else {
                                 $date = $value;
                             }
                             list($day, $month, $year) = explode('/', $date);
                             if (!checkdate($month, $day, $year)) {
                                 $field['showError'] = TRUE;
                                 $field['error'] = sprintf($this->ci->lang->line('incorrect_date_field'), $field['label']);
                             }
                         }
                     }
                 } else {
                     $hidden = $this->ci->input->post($field['name']);
                     if ($field['mandatory'] == TRUE && $_FILES[$field['name']]['error'] != 0 && !$hidden) {
                         $field['showError'] = TRUE;
                         $field['error'] = sprintf($this->ci->lang->line('incorrect_field'), $field['label']);
                     }
                     if ($_FILES[$field['name']]['error'] == 0) {
                         $temp = $this->saveTemporaryAttachments($field);
                         if (isset($temp[$field['name']]['error'])) {
                             $field['showError'] = TRUE;
                             $field['error'] = $temp[$field['name']]['error'];
                         } else {
                             $field['value'] = $temp[$field['name']]['file_name'];
                             $uploadData = array_merge($uploadData, $temp);
                         }
                     }
                 }
                 $fields[$index] = $field;
             }
         }
         $values = array();
         $checkErrors = FALSE;
         // The title and permalink are correct
         // (??)
         if (count($errors) == 0) {
             if (count($fields) > 0) {
                 foreach ($fields as $field) {
                     if (isset($field['error']) && $field['error'] != '') {
                         $checkErrors = TRUE;
                     }
                 }
             }
         }
         // ================ 3 - SAVE THE CONTENT VALUES ========================
         if (count($errors) == 0 && !$checkErrors) {
             $contentData = array('absolute_path' => $absolutePath) + array_intersect_key($this->ci->input->post(), array_flip(array('title', 'relative_path', 'lang')));
             // Save the basic content
             if (!$idContent) {
                 $contentData['id_content_type'] = $contentType['id'];
                 $contentData['id_user'] = $this->ci->fm_users_management->getLoggedUserId();
                 $idContent = $this->insertContent($contentData);
             } else {
                 $contentData['id'] = $idContent;
                 $this->updateContent($contentData);
                 if ($contentTypeName === 'pages' && isset($contentData['absolute_path']) && $contentData['absolute_path']) {
                     $this->ci->content->updateSonsPath($contentData['absolute_path'], $idContent);
                 }
             }
             $storeFolder = $this->_uploadPath . '/' . $idContent . '/';
             // I check if the directory of the content exists or not
             if (file_exists($storeFolder) == FALSE) {
                 mkdir($storeFolder, 0777);
             }
             // Create the thumb folder if image
             if (file_exists($storeFolder . 'thumbs/') == FALSE) {
                 mkdir($storeFolder . 'thumbs/', 0777);
             }
             $redirectURL .= $this->ci->input->post('save') ? $idContent : '';
             // Save the content values
             if (count($fields) > 0) {
                 // Move everything from the tmp folder to the content folder
                 $this->moveTemporaryAttachments($idContent);
                 foreach ($fields as $field) {
                     // ================ 4 - PROCESS THE IMAGES ===============
                     if ($field['type'] == 'image_upload' || $field['type'] == 'gallery') {
                         $hidden = $this->ci->input->post($field['name']);
                         if (isset($uploadData[$field['name']])) {
                             $processResult = $this->processImage($idContent, $field, $uploadData);
                             if (isset($processResult['error'])) {
                                 log_message($processResult['error']);
                             }
                         }
                     }
                     // Insert the value
                     if (!isset($contentValues[$field['id']])) {
                         if (!$this->isFilesystemField($field)) {
                             $value = $this->ci->input->post($field['name']);
                             if ($field['type'] == 'xhtml_textarea' && $tmpFolder) {
                                 $tmpFolder = $this->ci->config->item('txt_upl_img_path', 'factotum') . '/' . $tmpFolder;
                                 $value = str_replace($tmpFolder, $this->_imagesURL . '/' . $idContent, $value);
                             }
                             if ($field['type'] == 'multiselect' || $field['type'] == 'multicheckbox' || $field['type'] == 'multiple_linked_content') {
                                 $value = $value ? FM_Utility::convertMultiOptionsArrayToText($value) : '';
                             }
                             $this->insertContentValue($idContent, $field['id'], $value);
                         } else {
                             // Saving the Image/File Uploaded
                             if (($field['type'] == 'image_upload' || $field['type'] == 'file_upload') && isset($uploadData[$field['name']]['file_name'])) {
                                 if (isset($uploadData[$field['name']]['file_name'])) {
                                     $value = $uploadData[$field['name']]['file_name'];
                                 } else {
                                     // Retrieve the hidden value
                                     $value = $this->ci->input->post($field['name']);
                                 }
                                 $this->insertContentValue($idContent, $field['id'], $value);
                             }
                             // Saving the gallery
                             if ($field['type'] == 'gallery' && isset($uploadData[$field['name']])) {
                                 $idContentAttachment = $this->insertContentAttachment($idContent, $field['id'], $uploadData[$field['name']]['file_name'], $uploadData[$field['name']]['file_name']);
                                 $this->insertContentValue($idContent, $field['id'], $idContentAttachment);
                             }
                         }
                     } else {
                         // Update the existing rows
                         $cValue = $contentValues[$field['id']];
                         // Normal field type (text/textarea)
                         if (!$this->isFilesystemField($field)) {
                             $value = $this->ci->input->post($field['name']);
                             if ($field['type'] == 'xhtml_textarea' && $tmpFolder) {
                                 $tmpFolder = $this->ci->config->item('txt_upl_img_path', 'factotum') . '/' . $tmpFolder;
                                 $value = str_replace($tmpFolder, $this->_imagesURL . '/' . $idContent, $value);
                             }
                             if ($field['type'] == 'multiselect' || $field['type'] == 'multicheckbox' || $field['type'] == 'multiple_linked_content') {
                                 $value = FM_Utility::convertMultiOptionsArrayToText($value);
                             }
                             $this->updateContentValue($cValue['id'], $value);
                         } else {
                             // Saving the Image/File Uploaded
                             if (($field['type'] == 'image_upload' || $field['type'] == 'file_upload') && isset($uploadData[$field['name']]['file_name'])) {
                                 $value = $uploadData[$field['name']]['file_name'];
                                 $this->updateContentValue($cValue['id'], $value);
                             }
                             if ($field['type'] == 'gallery' && isset($uploadData[$field['name']])) {
                                 $idContentAttachment = $this->insertContentAttachment($idContent, $field['id'], $uploadData[$field['name']]['file_name'], $uploadData[$field['name']]['file_name']);
                                 $this->insertContentValue($idContent, $field['id'], $idContentAttachment);
                             }
                         }
                     }
                 }
                 // ================ 5 - EMPTY THE TMP FOLDER ===============
                 $this->deleteTmpFolder();
             }
             // 6 - SAVE THE CONTENT CATEGORIES
             $tmp = array();
             if (count($contentCategories) > 0) {
                 foreach ($contentCategories as $contentCategory) {
                     $tmp[] = $contentCategory['id_category'];
                 }
             }
             $contentCategories = $tmp;
             $postedCategories = $this->ci->input->post('categories');
             if ($postedCategories && count($postedCategories) > 0) {
                 if ($postedCategories) {
                     $tmp = array();
                     foreach ($postedCategories as $idContentCategory) {
                         $tmp[] = $idContentCategory;
                     }
                     $postedCategories = $tmp;
                 }
                 foreach ($categories as $cat) {
                     if (!in_array($cat['id'], $postedCategories)) {
                         $this->deleteContentCategoryByIdContentAndIdCategory($idContent, $cat['id']);
                     } else {
                         if (!in_array($cat['id'], $contentCategories)) {
                             $this->insertContentCategory($idContent, $cat['id']);
                         }
                     }
                 }
             } else {
                 foreach ($contentCategories as $idCategory) {
                     $this->deleteContentCategoryByIdContentAndIdCategory($idContent, $idCategory);
                 }
             }
             // ================ 7 - REDIRECT TO THE RESULT ===============
             $result['redirectURL'] = $redirectURL;
             $result['data_saved'] = TRUE;
         } else {
             $result['redirectURL'] = '';
         }
     }
     $result['fields'] = $fields;
     $result['errors'] = $errors;
     $result['oldValues'] = $oldValues;
     return $result;
 }
 /**
  * Retrieve the content list by content_type and some where condition
  *
  * @param	array          The where conditions array
  * @return	array          Return an array of content list
  */
 public function getContentList()
 {
     if (!$this->_idContentType) {
         return array();
     }
     try {
         // If the flag for the full info is setted to true, I retrieve also the data about the user, the date of last update, etc.
         if ($this->_fullInfo) {
             $this->_select .= $this->_contentTableName . '.id_user, ' . $this->_contentTableName . '.status, ' . $this->_contentTableName . '.data_insert, ' . $this->_contentTableName . '.data_last_update, ';
         }
         if ($this->_select != '*') {
             $this->_select = substr($this->_select, 0, -2);
         }
         if ($this->_allFields) {
             $this->_select .= ', ' . $this->_contentFieldTableName . '.name, ' . $this->_contentFieldTableName . '.type, ' . $this->_contentFieldTableName . '.linked_id_content_type, ' . $this->_contentValueTableName . '.value, ';
             $this->_select = substr($this->_select, 0, -2);
         }
         if ($this->_allCategories) {
             $this->_select .= ', ' . $this->_categoriesTableName . '.category_name, ' . $this->_categoriesTableName . '.category_label, ';
             $this->_select = substr($this->_select, 0, -2);
         }
         $this->_setBasicWhereConditions();
         $contentList = $this->ci->content->getContentList($this->_basicWhereConds, $this->_whereConditions, $this->_select, $this->_order, $this->_limit, $this->_offset, $this->_allFields, $this->_allCategories);
         if ($this->_allFields) {
             $contentList = $this->_parseContentFields($contentList);
         }
         if ($this->_allCategories) {
         }
         return $contentList;
     } catch (Exception $ex) {
         FM_Utility::debug($ex);
         die;
     }
 }
 private function _saveUser($idUser = null)
 {
     $result = array();
     $oldValues = array();
     $errors = array();
     $redirectURL = '/admin/users/';
     $useUsername = $this->config->item('use_username', 'factotum');
     $usernameMinLength = $this->config->item('username_min_length', 'factotum');
     $usernameMaxLength = $this->config->item('username_max_length', 'factotum');
     $passwordMinLength = $this->config->item('password_min_length', 'factotum');
     $passwordMaxLength = $this->config->item('password_max_length', 'factotum');
     $emailActivation = $this->config->item('email_activation', 'factotum');
     $activationPeriod = $this->config->item('email_activation_expire', 'factotum');
     $emailAccountDetails = $this->config->item('email_account_details', 'factotum');
     $siteName = $this->config->item('website_name', 'factotum');
     $this->data['useUsername'] = $useUsername;
     $result['data_saved'] = FALSE;
     $roles = $this->fm_users_management->getUserRolesList();
     $tmp = array();
     foreach ($roles as $role) {
         $tmp[$role['id']] = $role['role'];
     }
     $roles = $tmp;
     $this->data['roles'] = $roles;
     if ($idUser) {
         $user = $this->fm_users_management->getUserById($idUser);
         $userProfile = $this->fm_users_management->getUserProfileByIdUser($idUser);
         $oldValues['username'] = $user['username'];
         $oldValues['email'] = $user['email'];
         $oldValues['role'] = $user['id_user_role'];
         // Profile Fields
         $oldValues['firstname'] = $userProfile['firstname'];
         $oldValues['lastname'] = $userProfile['lastname'];
         $oldValues['dob'] = FM_Utility::convertIsoDateToHuman($userProfile['dob']);
     } else {
         $oldValues['username'] = '';
         $oldValues['email'] = '';
         $oldValues['role'] = '';
         // Profile Fields
         $oldValues['firstname'] = '';
         $oldValues['lastname'] = '';
         $oldValues['dob'] = '';
     }
     if ($useUsername) {
         $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[' . $usernameMinLength . ']|max_length[' . $usernameMaxLength . ']|alpha_dash');
         $this->form_validation->set_message('username', $this->lang->line('auth_incorrect_username'));
     }
     $this->form_validation->set_rules('role', 'Role', 'trim|required|xss_clean');
     $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
     $this->form_validation->set_message('email', $this->lang->line('auth_incorrect_email'));
     // Profile Fields
     $this->form_validation->set_rules('firstname', 'Firstname', 'trim|required|xss_clean');
     $this->form_validation->set_message('firstname', $this->lang->line('auth_incorrect_firstname'));
     $this->form_validation->set_rules('lastname', 'Lastname', 'trim|required|xss_clean');
     $this->form_validation->set_message('lastname', $this->lang->line('auth_incorrect_lastname'));
     $this->form_validation->set_rules('dob', 'Date of Birth', 'trim|required|xss_clean|callback_checkDob');
     $this->form_validation->set_message('dob', $this->lang->line('auth_incorrect_dob'));
     if ($this->input->post('add') || $this->input->post('save') && $this->input->post('password') != '') {
         $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[' . $passwordMinLength . ']|max_length[' . $passwordMaxLength . ']|alpha_dash');
         $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
     }
     if ($this->input->post('add') || $this->input->post('save')) {
         $redirectURL .= $this->input->post('save') ? 'edit/' . $idUser : '******';
         $oldValues['username'] = $useUsername ? $this->input->post('username') : '';
         $oldValues['email'] = $this->input->post('email');
         $oldValues['role'] = $this->input->post('role');
         // Profile Fields
         $oldValues['firstname'] = $this->input->post('firstname');
         $oldValues['lastname'] = $this->input->post('lastname');
         $oldValues['dob'] = $this->input->post('dob');
         // validation ok
         if ($this->form_validation->run()) {
             $password = $this->form_validation->set_value('password');
             $profileData = array('firstname' => $oldValues['firstname'], 'lastname' => $oldValues['lastname'], 'dob' => FM_Utility::convertHumanDateToIso($oldValues['dob']));
             if ($idUser) {
                 $userData = $this->fm_users_management->updateUser($idUser, $oldValues['email'], $oldValues['role'], $useUsername ? $oldValues['username'] : '');
                 if ($password) {
                     $this->fm_users_management->updatePassword($idUser, $password);
                 }
                 // Update the profile for the user
                 $this->fm_users_management->updateProfile($idUser, $profileData);
             } else {
                 $userData = $this->fm_users_management->insertUser($oldValues['username'], $oldValues['email'], $password, $oldValues['role'], $emailActivation);
                 // Insert the profile for the user
                 $this->fm_users_management->insertProfile($userData['id'], $profileData);
             }
             // success
             if (!is_null($userData)) {
                 if (!$idUser) {
                     $userData['siteName'] = $siteName;
                     $userData['activationPeriod'] = $activationPeriod / 3600;
                     if ($emailActivation) {
                         // send "activate" email
                         $this->fm_users_management->sendEmail('activate', $userData['email'], $userData);
                         // Clear password (just for any case)
                         unset($userData['password']);
                     } else {
                         // send "welcome" email
                         if ($emailAccountDetails) {
                             $this->fm_users_management->sendEmail('welcome', $userData['email'], $userData);
                         }
                         // Clear password (just for any case)
                         unset($userData['password']);
                     }
                 }
                 $result['redirectURL'] = $redirectURL;
                 $result['data_saved'] = TRUE;
             } else {
                 $authErrors = $this->fm_users_management->getErrorMessage();
                 foreach ($authErrors as $index => $errMsg) {
                     $errors[$index] = $this->lang->line($errMsg);
                 }
             }
         } else {
             $result['data_saved'] = FALSE;
             $result['redirectURL'] = '';
             if ($useUsername) {
                 $errors['username'] = form_error('username');
             }
             $errors['role'] = form_error('role');
             $errors['email'] = form_error('email');
             $errors['password'] = form_error('password');
             $errors['confirm_password'] = form_error('confirm_password');
             // Profiles Fields Errors
             $errors['firstname'] = form_error('firstname');
             $errors['lastname'] = form_error('lastname');
             $errors['dob'] = form_error('dob');
         }
     }
     $result['errors'] = $errors;
     $result['oldValues'] = $oldValues;
     return $result;
 }
 public function index()
 {
     $requestedPage = $_SERVER['REQUEST_URI'];
     if (!preg_match('/\\/(.*\\/)?([^\\/\\?]+)?(?:\\?.*)?$/', $_SERVER['REQUEST_URI'], $match)) {
         show_404($requestedPage, true);
     }
     $pagePath = isset($match[1]) ? $match[1] : '';
     // absolute path identifies a page
     $contentPath = isset($match[2]) ? $match[2] : null;
     // relative path identifies a content
     // var_dump($pagePath, $contentPath);
     // exit;
     if ($pagePath === '') {
         $this->home();
         return;
     }
     $pageSearch = new FM_ContentSearch();
     $pageSearch->initialize('pages')->onlyLiveContent(!$this->data['logged'])->addWhereCondition('absolute_path', '=', $pagePath)->fullInfo(true)->withAllFieldsAndValues(true);
     $page = $pageSearch->getContent();
     if (!$page || isset($page['only_logged_user']) && $page['only_logged_user'] && !$this->data['logged']) {
         show_404($requestedPage, TRUE);
     }
     $this->data['page'] = $page;
     $this->data['menu'] = $this->fm_cms->getMenu($this->data['logged'], $page['id']);
     $operation = $page['operation'];
     switch ($operation) {
         case 'content':
             // Retrieve the content and pass it to the view
             $contentSearch = new FM_ContentSearch();
             $contentSearch->initialize($page['content_types_list'])->onlyLiveContent(!$this->data['logged'])->withAllFieldsAndValues(TRUE)->withAllCategories(TRUE)->addWhereCondition('id', '=', $page['content_list'])->order(FM_Utility::getSQLOrderFromOption($page['content_list_order']));
             $content = $contentSearch->getContent();
             $contentCType = $this->fm_cms->getContentTypeById($content['id_content_type']);
             $contentCType = $contentCType['content_type'];
             $this->data['content'] = $content;
             if (file_exists(APPPATH . 'views/frontend/index/' . strtolower($page['template']) . '.php')) {
                 $this->view = 'frontend/index/' . strtolower($page['template']);
             } else {
                 $this->view = 'frontend/index/basic_content';
             }
             break;
         case 'content_list':
             // Retrieve the content list and pass it to the view
             $contentSearch = new FM_ContentSearch();
             $contentSearch->initialize($page['content_types_list'])->onlyLiveContent(!$this->data['logged'])->withAllFieldsAndValues(TRUE)->order(FM_Utility::getSQLOrderFromOption($page['content_list_order']));
             if (array_key_exists('content_list_categories', $page) && $page['content_list_categories']) {
                 $contentSearch->byCategories(is_array($page['content_list_categories']) ? $page['content_list_categories'] : explode(',', $page['content_list_categories']));
             }
             if ($contentPath) {
                 $contentSearch->addWhereCondition('relative_path', '=', $contentPath);
                 $content = $contentSearch->getContent();
                 $contentType = $this->fm_cms->getContentTypeById($content['id_content_type']);
                 $contentType = $contentType['content_type'];
                 $this->data['contentType'] = $contentType;
                 $this->data['content'] = $content;
             } else {
                 if ($this->input->get('per_page')) {
                     // Start the offset from 1 (issue in the CodeIgniter Pagination Class)
                     $contentSearch->offset($this->input->get('per_page') + 1);
                 }
                 if ($page['content_list_num_per_page']) {
                     $contentSearch->limit($page['content_list_num_per_page']);
                 }
                 $contentList = $contentSearch->getContentList();
                 // TODO: complete
                 $this->data['pagination'] = $page['content_list_pagination'] == 'yes' ? TRUE : FALSE;
                 if ($this->data['pagination']) {
                     $this->pagination(site_url() . "/{$page['absolute_path']}?", $contentSearch->getContentListCount(), $page['content_list_num_per_page']);
                 }
                 $this->data['contentList'] = $contentList;
             }
             if (file_exists(APPPATH . 'views/frontend/index/' . strtolower($page['template']) . '.php')) {
                 $this->view = 'frontend/index/' . strtolower($page['template']);
             } else {
                 $this->view = 'frontend/index/basic_content_list';
             }
             break;
         case 'action':
             $action = $page['action'];
             $this->{$action}();
             if (file_exists(APPPATH . 'views/frontend/index/' . strtolower($action) . '.php')) {
                 $this->view = 'frontend/index/' . strtolower($action);
             } else {
                 $this->view = 'frontend/index/' . $page['template'];
             }
             break;
         case 'text':
             $this->view = 'frontend/index/basic_content';
             break;
         case 'link':
             $this->output->set_status_header(303, 'See Other');
             header('Location: ' . $page['link']);
             exit;
             break;
     }
     // Special template for ajax Calls
     if ($page['template'] == 'ajax') {
         $this->layout = FALSE;
         $this->view = FALSE;
     }
     // 		} else {
     //
     // 			if (file_exists(APPPATH . 'views/frontend/index/basic_' . strtolower($contentType) . '.php')) {
     //
     // 				$this->view = 'frontend/index/basic_' . strtolower($contentType);
     //
     // 			} else {
     //
     // 				$this->view = 'frontend/index/basic_content';
     //
     // 			}
     //
     // 		}
 }
 /**
  * Register user on the site
  *
  * @return void
  */
 public function register()
 {
     $oldValues = array();
     $errors = array();
     $allowRegistration = $this->config->item('allow_registration', 'factotum');
     $useUsername = $this->config->item('use_username', 'factotum');
     $usernameMinLength = $this->config->item('username_min_length', 'factotum');
     $usernameMaxLength = $this->config->item('username_max_length', 'factotum');
     $passwordMinLength = $this->config->item('password_min_length', 'factotum');
     $passwordMaxLength = $this->config->item('password_max_length', 'factotum');
     $emailActivation = $this->config->item('email_activation', 'factotum');
     $activationPeriod = $this->config->item('email_activation_expire', 'factotum');
     $emailAccountDetails = $this->config->item('email_account_details', 'factotum');
     $siteName = $this->config->item('website_name', 'factotum');
     $captchaRegistration = $this->config->item('captcha_registration', 'factotum');
     $useRecaptcha = $this->config->item('use_recaptcha', 'factotum');
     $role = $this->fm_users_management->getRoleByRoleName('user');
     $this->data['useUsername'] = $useUsername;
     $this->data['captchaRegistration'] = $captchaRegistration;
     $this->data['useRecaptcha'] = $useRecaptcha;
     // logged in
     if ($this->fm_users_management->isLoggedIn()) {
         redirect('/');
     } elseif ($this->fm_users_management->isLoggedInButNotActive()) {
         // logged in, not activated
         redirect('/send-again/');
     } elseif (!$allowRegistration) {
         // registration is off
         $errors['generic'] = $this->lang->line('auth_message_registration_disabled');
     } else {
         if ($useUsername) {
             $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[' . $usernameMinLength . ']|max_length[' . $usernameMaxLength . ']|alpha_dash');
         }
         if ($captchaRegistration) {
             if ($useRecaptcha) {
                 $this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback_checkRecaptcha');
                 $this->data['recaptchaHtml'] = $this->fm_users_management->createRecaptcha();
             } else {
                 $this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback_checkCaptcha');
                 $this->data['captchaHtml'] = $this->fm_users_management->createCaptcha();
             }
         }
         $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
         $this->form_validation->set_message('email', $this->lang->line('auth_incorrect_email'));
         $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[' . $passwordMinLength . ']|max_length[' . $passwordMaxLength . ']|alpha_dash');
         $this->form_validation->set_message('password', $this->lang->line('auth_incorrect_password'));
         $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
         $this->form_validation->set_message('confirm_password', $this->lang->line('auth_incorrect_confirm_password'));
         // Profile Fields
         $this->form_validation->set_rules('firstname', 'Firstname', 'trim|required|xss_clean');
         $this->form_validation->set_message('firstname', $this->lang->line('auth_incorrect_firstname'));
         $this->form_validation->set_rules('lastname', 'Lastname', 'trim|required|xss_clean');
         $this->form_validation->set_message('lastname', $this->lang->line('auth_incorrect_lastname'));
         $this->form_validation->set_rules('dob', 'Date of Birth', 'trim|required|xss_clean|callback_checkDob');
         $this->form_validation->set_message('dob', $this->lang->line('auth_incorrect_dob'));
         $oldValues['username'] = '';
         $oldValues['email'] = '';
         // Profile Fields
         $oldValues['firstname'] = '';
         $oldValues['lastname'] = '';
         $oldValues['dob'] = '';
         if ($this->input->post('register')) {
             $oldValues['username'] = $useUsername ? $this->input->post('username') : '';
             $oldValues['email'] = $this->input->post('email');
             // Profile Fields
             $oldValues['firstname'] = $this->input->post('firstname');
             $oldValues['lastname'] = $this->input->post('lastname');
             $oldValues['dob'] = $this->input->post('dob');
             // validation ok
             if ($this->form_validation->run()) {
                 $password = $this->form_validation->set_value('password');
                 $userData = $this->fm_users_management->insertUser($oldValues['username'], $oldValues['email'], $password, $role['id'], $emailActivation);
                 $profileData = array('firstname' => $oldValues['firstname'], 'lastname' => $oldValues['lastname'], 'dob' => FM_Utility::convertHumanDateToIso($oldValues['dob']));
                 // success
                 if (!is_null($userData)) {
                     // Insert the profile for the user
                     $this->fm_users_management->insertProfile($userData['id'], $profileData);
                     $userData['siteName'] = $siteName;
                     $userData['activationPeriod'] = $activationPeriod / 3600;
                     if ($emailActivation) {
                         // send "activate" email
                         $this->fm_users_management->sendEmail('activate', $userData['email'], $userData);
                         // Clear password (just for any case)
                         unset($userData['password']);
                     } else {
                         // send "welcome" email
                         if ($emailAccountDetails) {
                             $this->fm_users_management->sendEmail('welcome', $userData['email'], $userData);
                         }
                         // Clear password (just for any case)
                         unset($userData['password']);
                     }
                     redirect('/registration-complete');
                 } else {
                     $authErrors = $this->fm_users_management->getErrorMessage();
                     foreach ($authErrors as $index => $errMsg) {
                         $errors[$index] = $this->lang->line($errMsg);
                     }
                 }
             } else {
                 if ($useUsername) {
                     $errors['username'] = form_error('username');
                 }
                 $errors['email'] = form_error('email');
                 $errors['password'] = form_error('password');
                 $errors['confirm_password'] = form_error('confirm_password');
                 $errors['captcha'] = form_error('captcha');
                 $errors['recaptcha_response_field'] = form_error('recaptcha_response_field');
                 // Profiles Fields Errors
                 $errors['firstname'] = form_error('firstname');
                 $errors['lastname'] = form_error('lastname');
                 $errors['dob'] = form_error('dob');
             }
         }
     }
     $this->data['errors'] = $errors;
     $this->data['oldValues'] = $oldValues;
 }
 private function _saveContentField($idContentType = null, $idContentField = null)
 {
     $result = array();
     $oldValues = array();
     $errors = array();
     $result['data_saved'] = FALSE;
     if ($idContentField) {
         $contentField = $this->fm_cms->getContentFieldById($idContentField);
         $oldValues['name'] = $contentField['name'];
         $oldValues['label'] = $contentField['label'];
         $oldValues['hint'] = $contentField['hint'];
         $oldValues['mandatory'] = $contentField['mandatory'] ? 'true' : 'false';
         $oldValues['type'] = $contentField['type'];
         $oldValues['max_file_size'] = $contentField['max_file_size'];
         $oldValues['allowed_types'] = $contentField['allowed_types'];
         $oldValues['max_image_size'] = $contentField['max_image_size'];
         $oldValues['thumb_size'] = $contentField['thumb_size'];
         $oldValues['image_operation'] = $contentField['image_operation'];
         $oldValues['image_bw'] = $contentField['image_bw'];
         $oldValues['linked_id_content_type'] = $contentField['linked_id_content_type'];
         $oldValues['options']['values'] = array();
         $oldValues['options']['labels'] = array();
         if (in_array($oldValues['type'], array('radio', 'select', 'multiselect', 'checkbox', 'multicheckbox'))) {
             $options = fm_Utility::convertOptionsTextToArray($contentField['options']);
             $oldValues['options']['values'] = array_keys($options);
             $oldValues['options']['labels'] = array_values($options);
         }
     } else {
         $oldValues['name'] = '';
         $oldValues['label'] = '';
         $oldValues['hint'] = '';
         $oldValues['mandatory'] = '';
         $oldValues['type'] = '';
         $oldValues['max_file_size'] = '';
         $oldValues['allowed_types'] = '';
         $oldValues['max_image_size'] = '';
         $oldValues['thumb_size'] = '';
         $oldValues['image_operation'] = '';
         $oldValues['image_bw'] = '';
         $oldValues['linked_id_content_type'] = '';
     }
     if ($this->input->post('add') || $this->input->post('save') && $this->input->post('name') != $oldValues['name']) {
         $this->form_validation->set_rules('name', 'Field Name', 'trim|required|xss_clean|alpha_dash|callback_checkFieldName');
         $this->form_validation->set_message('name', $this->lang->line('incorrect_content_field_name'));
     }
     $this->form_validation->set_rules('label', 'Field Label', 'trim|required|xss_clean');
     $this->form_validation->set_message('label', $this->lang->line('incorrect_content_field_label'));
     $this->form_validation->set_rules('mandatory', 'Mandatory', 'trim|required|xss_clean');
     $this->form_validation->set_message('mandatory', $this->lang->line('incorrect_content_field_mandatory'));
     $this->form_validation->set_rules('type', 'Field Type', 'trim|required|xss_clean');
     $this->form_validation->set_message('type', $this->lang->line('incorrect_content_field_type'));
     if ($this->input->post('add') || $this->input->post('save')) {
         $oldValues['name'] = $this->input->post('name');
         $oldValues['type'] = $this->input->post('type');
         $oldValues['label'] = $this->input->post('label');
         $oldValues['hint'] = $this->input->post('hint');
         $oldValues['mandatory'] = $this->input->post('mandatory');
         if ($this->input->post('type') == 'file_upload' || $this->input->post('type') == 'image_upload' || $this->input->post('type') == 'gallery') {
             $oldValues['max_file_size'] = $this->input->post('max_file_size');
             $oldValues['allowed_types'] = $this->input->post('allowed_types');
             $this->form_validation->set_rules('max_file_size', 'Max File Size', 'trim|required|xss_clean|integer');
             $this->form_validation->set_message('max_file_size', $this->lang->line('incorrect_max_file_size'));
             $this->form_validation->set_rules('allowed_types', 'Allowed Types', 'trim|required|xss_clean');
             $this->form_validation->set_message('allowed_types', $this->lang->line('incorrect_allowed_types'));
             if ($this->input->post('type') == 'image_upload' || $this->input->post('type') == 'gallery') {
                 $oldValues['max_image_size'] = $this->input->post('max_image_size');
                 $oldValues['thumb_size'] = $this->input->post('thumb_size');
                 $oldValues['image_operation'] = $this->input->post('image_operation');
                 $oldValues['image_bw'] = $this->input->post('image_bw');
                 $this->form_validation->set_rules('max_image_size', 'Max Image Size', 'trim|required|xss_clean');
                 $this->form_validation->set_message('max_image_size', $this->lang->line('incorrect_max_image_size'));
                 $this->form_validation->set_rules('thumb_size', 'Thumb Size', 'trim|required|xss_clean');
                 $this->form_validation->set_message('thumb_size', $this->lang->line('incorrect_thumb_size'));
                 $this->form_validation->set_rules('image_operation', 'Image Operation', 'trim|required|xss_clean');
                 $this->form_validation->set_message('image_operation', $this->lang->line('incorrect_image_operation'));
             }
         } else {
             $oldValues['max_file_size'] = '';
             $oldValues['allowed_types'] = '';
         }
         if (in_array($this->input->post('type'), array('linked_content', 'multiple_linked_content'))) {
             $oldValues['linked_id_content_type'] = $this->input->post('linked_id_content_type');
             $this->form_validation->set_rules('linked_id_content_type', 'Linked Content Type', 'trim|required|xss_clean');
             $this->form_validation->set_message('linked_id_content_type', $this->lang->line('incorrect_linked_id_content_type'));
         } else {
             $oldValues['linked_id_content_type'] = '';
         }
         if ($this->input->post('type') == 'radio' || $this->input->post('type') == 'select' || $this->input->post('type') == 'multiselect' || $this->input->post('type') == 'checkbox' || $this->input->post('type') == 'multicheckbox') {
             $options = $this->input->post('options');
             if ($options) {
                 $oldValues['options']['values'] = $options['values'];
                 $oldValues['options']['labels'] = $options['labels'];
                 if (isset($oldValues['options']['values']) && count($oldValues['options']['values']) == 0) {
                     $errors['options']['values'][0] = $this->lang->line('incorrect_options_values');
                 }
                 if (isset($oldValues['options']['labels']) && count($oldValues['options']['labels']) == 0) {
                     $errors['options']['labels'][0] = $this->lang->line('incorrect_options_labels');
                 }
             }
         }
         if ($this->form_validation->run()) {
             $extra = array();
             $extra['hint'] = $oldValues['hint'];
             if (in_array($oldValues['type'], array('select', 'multiselect', 'radio', 'checkbox', 'multicheckbox'))) {
                 $options = array();
                 foreach ($oldValues['options']['values'] as $index => $value) {
                     if ($value != '') {
                         $options[] = FM_Utility::cleanString($value) . ':' . $oldValues['options']['labels'][$index];
                     }
                 }
                 $extra['options'] = join("\n", $options);
             }
             if (in_array($oldValues['type'], array('file_upload', 'image_upload', 'gallery'))) {
                 $extra['max_file_size'] = $oldValues['max_file_size'];
                 $extra['allowed_types'] = $oldValues['allowed_types'];
             }
             if (in_array($oldValues['type'], array('image_upload', 'gallery'))) {
                 $extra['max_image_size'] = $oldValues['max_image_size'];
                 $extra['thumb_size'] = $oldValues['thumb_size'];
                 $extra['image_operation'] = $oldValues['image_operation'];
                 $extra['image_bw'] = $oldValues['image_bw'];
             }
             if (in_array($oldValues['type'], array('linked_content', 'multiple_linked_content'))) {
                 $extra['linked_id_content_type'] = $oldValues['linked_id_content_type'];
             }
             $oldValues['mandatory'] = $oldValues['mandatory'] == 'true' ? TRUE : FALSE;
             if (!$idContentField) {
                 $this->fm_cms->insertContentField($idContentType, $oldValues['name'], $oldValues['type'], $oldValues['label'], $oldValues['mandatory'], '', $extra);
             } else {
                 $this->fm_cms->updateContentField($idContentField, $oldValues['name'], $oldValues['type'], $oldValues['label'], $oldValues['mandatory'], '', $extra);
             }
             $result['data_saved'] = TRUE;
         } else {
             $errors['name'] = form_error('name');
             $errors['label'] = form_error('label');
             $errors['mandatory'] = form_error('mandatory');
             $errors['type'] = form_error('type');
             $errors['options']['values'] = form_error('options[values]');
             $errors['options']['labels'] = form_error('options[labels]');
             $errors['max_file_size'] = form_error('max_file_size');
             $errors['allowed_types'] = form_error('allowed_types');
             $errors['max_image_size'] = form_error('max_image_size');
             $errors['thumb_size'] = form_error('thumb_size');
             $errors['image_operation'] = form_error('image_operation');
         }
     }
     $result['errors'] = $errors;
     $result['oldValues'] = $oldValues;
     return $result;
 }