Exemplo n.º 1
0
 /**
  * Basic
  */
 public function action_edit()
 {
     $this->title = __('settings.settings_general');
     // Fields for save
     $for_extract = ['per_page_frontend', 'per_page_backend', 'sitename', 'siteslogan', 'copyright', 'year_creation_site', 'type_backend_menu'];
     $config = Config::get('settings');
     $data = Arr::extract($_POST, $for_extract);
     if ($this->request->is_post()) {
         $data = Validation::factory(array_map('trim', $data))->rules('per_page_frontend', [['not_empty'], ['digit']])->rules('per_page_backend', [['not_empty'], ['digit']])->rules('year_creation_site', [['not_empty'], ['digit']])->rule('sitename', 'not_empty');
         if ($data->check()) {
             foreach ($for_extract as $field) {
                 $config[$field] = $data[$field];
             }
             $config->save();
             Message::success(__('settings.changes_saved'));
             HTTP::redirect(Route::url('b_settings'));
         } else {
             Message::error(__('settings.error_saving'));
             $errors = $data->errors('validation');
         }
     } else {
         $data = $config;
     }
     $this->content = View::factory($this->view, ['data' => $data])->bind('errors', $errors);
 }
Exemplo n.º 2
0
 /**
  * Init
  */
 public function init()
 {
     parent::init();
     if ($dsn = $this->get('database.dsn')) {
         $config = parse_url($dsn);
         if (isset($config['query'])) {
             parse_str($config['query'], $query);
             $config += $query;
         }
         if (!isset($config['host'])) {
             $config['host'] = 'localhost';
         }
         if (!isset($config['user'])) {
             $config['user'] = '******';
         }
         if (!isset($config['pass'])) {
             $config['pass'] = '';
         }
         if (!isset($config['prefix'])) {
             $config['prefix'] = $this->get('database.default_prefix', '');
         }
         $config['database'] = trim($config['path'], '/');
         $driver = 'Db_Driver_' . ucfirst($config['scheme']);
         if (!class_exists($driver)) {
             return Message::error(t('Database driver <b>%s</b> not found.', 'Database errors', ucfirst($config['scheme'])));
         }
         $this->driver = new $driver($config);
         $this->hook('done', array($this, 'showErrors'));
         $this->hook('debug', array($this, 'trace'));
         cogear()->db = $this->driver;
     } else {
         die('Couldn\'t connect to database.');
     }
 }
Exemplo n.º 3
0
 public static function display()
 {
     $messages = "";
     if ($_POST['cc_form'] === 'add-group') {
         $group = $_POST['group'];
         $rows = Database::select('users', 'name', array('name = ? AND type = ?', $group, 'group'), null, 1)->fetch(PDO::FETCH_ASSOC);
         if (!empty($rows)) {
             $messages .= Message::error(__('admin', 'group-in-use'));
         } else {
             $row = DB::select('users', array('data'), array('users_id = ?', $_GET['parent']))->fetch(PDO::FETCH_ASSOC);
             $inheritance = unserialize($row['data']);
             $inheritance = $inheritance['permissions'];
             $result = Database::insert('users', array('name' => filter('admin_add_group_name', $group), 'type' => 'group', 'group' => '-1', 'data' => serialize(filter('admin_add_group_data', array('permissions' => $inheritance)))));
             if ($result === 1) {
                 $messages .= Message::success(__('admin', 'group-added'));
             }
         }
     }
     $form = new Form('self', 'post', 'add-group');
     $form->startFieldset(__("admin", 'group-information'));
     $form->addInput(__('admin', 'group-name'), 'text', 'group', self::get('group'));
     $groups = Users::allGroups();
     foreach ($groups as $key => $value) {
         $groups[$value->getId()] = $value->getName();
     }
     $form->addSelectList(__('admin', 'inherit-permissions'), 'parent', $groups);
     plugin('admin_add_group_custom_fields', array(&$form));
     $form->addSubmit('', 'add-group', __('admin', 'add-group'));
     $form->endFieldset();
     plugin('admin_add_group_custom_fieldset', array(&$form));
     $form = $form->endAndGetHTML();
     return array(__('admin', 'add-group'), $messages . $form);
 }
Exemplo n.º 4
0
 /**
  * Runs all the methods to store the various settings from the shop
  * admin zone.
  *
  * Note that not all of the methods report their success or failure back
  * here (yet), so you should not rely on the result of this method.
  * @return  mixed               True on success, false on failure,
  *                              null if no change is detected.
  * @static
  */
 static function storeSettings()
 {
     global $_CORELANG;
     self::$success = true;
     self::$changed = false;
     self::storeGeneral();
     self::storeCurrencies();
     self::storePayments();
     self::storeShipping();
     self::storeCountries();
     $result = Zones::store_from_post();
     if (isset($result)) {
         self::$changed = true;
         self::$success &= $result;
     }
     self::storeVat();
     if (\Cx\Core\Setting\Controller\Setting::changed()) {
         self::$changed = true;
         if (\Cx\Core\Setting\Controller\Setting::updateAll() === false) {
             return false;
         }
     }
     if (self::$changed) {
         return self::$success ? \Message::ok($_CORELANG['TXT_CORE_SETTING_STORED_SUCCESSFULLY']) : \Message::error($_CORELANG['TXT_CORE_SETTING_ERROR_STORING']);
     }
     return null;
 }
Exemplo n.º 5
0
 public function action_edit($img_id = 0)
 {
     $this->template->title = __("Thêm hình ảnh slide");
     $this->template->section_title = __("Thêm hình ảnh slide");
     $data = array();
     $img = ImageSlide::BLL()->find($img_id);
     if (!$img) {
         Message::error('Không tìm thấy hình ảnh');
         Request::instance()->redirect('/admin/slide/index');
     }
     if (Request::$method == "POST") {
         $post = $img->validate_update($_POST);
         if ($post->check()) {
             $post = $post->as_array();
             $img->src = $post['src'];
             $img->slide_position = $post['slide_position'];
             $img->url = $post['url'];
             $img->order = intval($post['order']);
             $img->User = Auth::instance()->get_user();
             $img->description = $post['description'];
             $img->save();
             Message::success('Cập nhập thông tin hình ảnh slide thành công!');
             Request::instance()->redirect('/admin/slide/by_pos/' . $img->slide_position . '.html');
         } else {
             $data['errors'] = $post->errors('admin/slide');
             $_POST = $post->as_array();
         }
     }
     $data['image'] = $img->toArray();
     $this->template->content = View::factory('admin/slide/edit', $data);
 }
Exemplo n.º 6
0
 /**
  * Edit
  */
 public function action_edit()
 {
     $this->title = __('home.page_edit');
     // Fields for save
     $for_extract = ['text', 'meta_t', 'meta_d', 'meta_k'];
     $config = Config::get('home');
     $data = Arr::extract($_POST, $for_extract);
     if ($this->request->is_post()) {
         $data = Validation::factory(array_map('trim', $data))->rule('meta_t', 'not_empty')->rule('meta_d', 'not_empty')->rule('meta_k', 'not_empty');
         if ($data->check()) {
             foreach ($for_extract as $field) {
                 $config[$field] = $data[$field];
             }
             $config->save();
             Message::success(__('settings.changes_saved'));
             HTTP::redirect(Route::url('b_home'));
         } else {
             Message::error(__('settings.error_saving'));
             $errors = $data->errors('validation');
         }
     } else {
         $data = $config;
     }
     $this->content = View::factory($this->view, ['data' => $data])->bind('errors', $errors);
 }
Exemplo n.º 7
0
 /**
  * Formats setting
  *
  * @uses  InputFilter::filters
  * @uses  Assets::tabledrag
  * @uses  Config::load
  * @uses  Message::error
  * @uses  Filter::all
  */
 public function action_configure()
 {
     $id = $this->request->param('id', NULL);
     // Get required format
     $format = $this->_format->get($id);
     $config = Config::load('inputfilter');
     if (is_null($format)) {
         Log::error('Attempt to access non-existent format id :id', array(':id' => $id));
         Message::error(__('Text Format doesn\'t exists!'));
         $this->request->redirect(Route::get('admin/format')->uri(), 404);
     }
     $fallback_format = (int) $config->default_format;
     $formats = $this->_format->get_all();
     $formats[$id]['id'] = $id;
     $all_roles = ORM::factory('role')->find_all()->as_array('id', 'name');
     $filters = Filter::all();
     $enabled_filters = $formats[$id]['filters'];
     // Form attributes
     $params = array('id' => $id, 'action' => 'configure');
     $this->title = __('Configure %name format', array('%name' => $format['name']));
     $view = View::factory('admin/format/form')->set('roles', $all_roles)->set('filters', $filters)->set('enabled_filters', $enabled_filters)->set('format', $format)->set('params', $params);
     if ($this->valid_post('filter')) {
         unset($_POST['filter'], $_POST['_token'], $_POST['_action']);
         Message::info(__('Not implemented yet!'));
     }
     $this->response->body($view);
     Assets::tabledrag();
 }
Exemplo n.º 8
0
 /**
  * Displays an edit page form.
  *
  * Route: admin/pages/edit/:num
  *
  * @param int $id The id of the page to edit
  */
 public static function edit($id)
 {
     if (isset($_POST['update_page']) && Html::form()->validate()) {
         $status = Page::page()->where('id', '=', $id)->update(array('page_id' => $_POST['page_id'], 'title' => $_POST['title'], 'slug' => $_POST['slug'], 'body' => $_POST['body']));
         if ($status) {
             Message::ok('Page updated successfully.');
         } else {
             Message::error('Error updating page. Please try again.');
         }
     }
     $page = Page::page()->find($id);
     // Either get all pages or only current users pages based on permission
     if (!User::current()->hasPermission('page.manage')) {
         $pages = Page::page()->where('user_id', '=', User::current())->andWhere('id', '!=', $id)->all();
     } else {
         $pages = Page::page()->where('id', '!=', $id)->all();
     }
     MultiArray::load($pages, 'page_id');
     $indentedPages = MultiArray::indent();
     $arrPages = array(0 => '-');
     foreach ($indentedPages as $p) {
         $arrPages[$p->id] = $p->indent . $p->title;
     }
     $fields[] = array('fields' => array('page_id' => array('title' => 'Parent', 'type' => 'select', 'options' => $arrPages, 'selected' => $page->page_id), 'title' => array('title' => 'Title', 'type' => 'text', 'default_value' => $page->title, 'validate' => array('required')), 'slug' => array('title' => 'Slug', 'type' => 'text', 'default_value' => $page->slug, 'validate' => array('required')), 'body' => array('title' => 'Body', 'type' => 'textarea', 'default_value' => $page->body, 'attributes' => array('class' => 'tinymce')), 'update_page' => array('value' => 'Update Page', 'type' => 'submit')));
     return array(array('title' => 'Edit Page', 'content' => Html::form()->build($fields)));
 }
Exemplo n.º 9
0
 public function action_user()
 {
     $id = (int) $this->request->param('id', 0);
     $post = ORM::factory('user', $id);
     if (!$post->loaded() or $id === 1) {
         Message::error(__("User doesn't exists!"));
         Log::error('Attempt to access non-existent user.');
         $this->request->redirect(Route::get('admin/user')->uri(array('action' => 'list')), 404);
     }
     $this->title = __(':user Permissions', array(":user" => $post->name));
     $action = Route::get('admin/permission')->uri(array('action' => 'user', 'id' => isset($post->id) ? $post->id : 0));
     $view = View::factory('admin/permission/user')->set('post', $post)->set('oldperms', $post->perms())->set('permissions', ACL::all())->set('action', $action)->bind('errors', $this->_errors);
     if ($this->valid_post('permissions')) {
         $perms = array_filter($_POST['perms']);
         $post->data = array('permissions' => $perms);
         try {
             $post->save();
             Message::success(__('Permissions: saved successful!'));
             $this->request->redirect(Route::get('admin/permission')->uri(array('action' => 'user', 'id' => $post->id)));
         } catch (ORM_Validation_Exception $e) {
             Message::error(__('Permissions save failed!'));
             $this->_errors = $e->errors('models', TRUE);
         } catch (Exception $e) {
             Message::error(__('Permissions save failed!'));
             $this->_errors = array($e->getMessage());
         }
     }
     $this->response->body($view);
 }
Exemplo n.º 10
0
 protected function testTheEnvironment()
 {
     $message = new Message();
     if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300) {
         $message->error('HTMLy requires at least PHP 5.3 to run.');
     }
     if (!in_array('https', stream_get_wrappers())) {
         $message->error('Installer needs the https wrapper, please install openssl.');
     }
     if (function_exists('apache_get_modules') && !in_array('mod_rewrite', apache_get_modules())) {
         $message->warning('mod_rewrite must be enabled if you use Apache.');
     }
     if (!is__writable("./")) {
         $message->error('no permission to write in the Directory.');
     }
     return $message->run();
 }
Exemplo n.º 11
0
 /**
  * Determines if there where any errors in the previous validation checks. If there was,
  * it sets an error message. Once can optionally set the error message.
  *
  * @param string The error message to display if validation failed (Optional)
  * @return boolean.
  */
 public static function passed($message = 'Missing or invalid fields.')
 {
     if (!self::$_errors) {
         return true;
     }
     Message::error($message);
     return false;
 }
Exemplo n.º 12
0
 public function messages(Message $message)
 {
     $this->tpl->error = $message->error();
     $this->tpl->success = $message->success();
     $this->tpl->alert = $message->alert();
     $this->tpl->info = $message->info();
     $this->tpl->debug = $message->debug();
 }
Exemplo n.º 13
0
 /**
  * Deletes a language and redirect to admin/multilanguage/languages/manage
  *
  * Route: admin/multilanguage/languages/delete/:num
  *
  * @param int $id The id of the language to delete.
  */
 public static function delete($id)
 {
     if (Multilanguage::language()->delete($id)) {
         Message::ok('Language deleted successfully.');
     } else {
         Message::error('Error deleting language, please try again.');
     }
     Url::redirect('admin/multilanguage/languages/manage');
 }
Exemplo n.º 14
0
 /**
  * Constructor
  *
  * @param array $config
  */
 public function __construct(array $config)
 {
     $this->config = array_merge($this->config, $config);
     try {
         $this->open();
     } catch (Db_Exception $e) {
         Message::error($e->getMessage());
     }
 }
Exemplo n.º 15
0
 public static function login()
 {
     if ($_POST) {
         $user = User::user()->where('email', '=', $_POST['email'])->andWhere('pass', '=', md5($_POST['password']))->first();
         if ($user) {
             $_SESSION[Config::get('user.session_key')] = $user->id;
             Url::redirect('admin');
         } else {
             Message::error('Invalid login details.');
         }
     }
 }
Exemplo n.º 16
0
 public function changePW($pw)
 {
     $pw = $this->createHash($pw);
     try {
         $stmt = $this->db->prepare('UPDATE users SET password = ? WHERE id = ?');
         $stmt->bindParam('1', $pw);
         $stmt->bindParam('2', $_SESSION['userid']);
         $stmt->execute();
         return true;
     } catch (PDOException $e) {
         $message = new Message();
         $message->error("error_sql", $e->getMessage());
         return false;
     }
 }
Exemplo n.º 17
0
 /**
  * Used to run the admin install if it hasn't been created yet.
  */
 public static function install()
 {
     if ($_POST) {
         Validate::check('email', array('email'));
         Validate::check('password', array('required'));
         Validate::check('conf_password', array('matches:password'));
         if (Validate::passed()) {
             $userId = User::user()->insert(array('email' => $_POST['email'], 'pass' => md5($_POST['password']), 'is_admin' => 1));
             if ($userId) {
                 Message::ok('Admin install complete.');
                 Url::redirect('admin/login');
             } else {
                 Message::error('Error creating admin account. Please try again.');
             }
         }
     }
 }
Exemplo n.º 18
0
 /**
  * Before action
  *
  * @throws HTTP_Exception_403
  */
 public function before()
 {
     parent::before();
     $this->auth = Auth::instance();
     $this->user = $this->auth->get_user();
     $this->is_admin = $this->auth->logged_in('admin');
     // Проверяем права на доступ к текущей странице
     if ($this->auth_required !== false and $this->auth->logged_in($this->auth_required) === false or is_array($this->secure_actions) and array_key_exists($this->request->action(), $this->secure_actions) and $this->auth->logged_in($this->secure_actions[$this->request->action()]) === false) {
         // Если нет прав и AJAX запрос, то выдаем эксепшен
         if ($this->auth->logged_in() and $this->request->is_ajax()) {
             throw new HTTP_Exception_403('Unauthorised access attempt');
         } else {
             throw new HTTP_Exception_403('Unauthorised access attempt');
             Message::error(__('Unauthorised access attempt!'));
             HTTP::redirect(Route::url('f_home'));
         }
     }
 }
Exemplo n.º 19
0
 public static function display()
 {
     if (!is_numeric($_GET['id'])) {
         cc_redirect(Admin::link('users'));
     }
     if ($_POST['cc_form'] == 'edit-group') {
         $id = $_GET['id'];
         $previous = (array) unserialize(urldecode($_POST['previous']));
         $group = $_POST['group'];
         $permissions = (array) $_POST['permissions'];
         $new = array_merge($previous, $permissions);
         foreach ($new as $k => $v) {
             if ($v == "1") {
                 $new[$k] = true;
             }
             if (!array_key_exists($k, $permissions)) {
                 $new[$k] = false;
             }
         }
         if (DB::update('users', array('name', 'data'), array($group, serialize(filter('admin_edit_group_data', array('permissions' => $new)))), array('users_id = ?', $id))) {
             $message = Message::success(__('admin', 'group-information-updated'));
         } else {
             $message = Message::error(__('admin', 'database-error'));
         }
     }
     $p = Permissions::getAll();
     $g = new Group((int) $_GET['id']);
     $p_form = new Form('');
     $p_form->setCC_Form('edit-group');
     $p_form->startFieldset(__('admin', 'group-information'));
     $p_form->addInput(__('admin', 'group-name'), 'text', 'group', $g->getName());
     $p_form->endFieldset();
     $p_form->addHTML(sprintf("<h3>%s</h3>", __('admin', 'permissions')));
     $p_table = new Table('permissions');
     $p_table->addHeader(array('Name', 'Allowed'));
     foreach ($p as $k => $v) {
         $previous[$v['name']] = $g->isAllowed($v['name']);
         $p_table->addRow(array(__('permissions', $v['name']), sprintf('<input type="checkbox" name="permissions[%s]"%svalue="1"/>', $v['name'], $g->isAllowed($v['name']) ? ' checked="checked"' : '')));
     }
     $p_form->addHidden('previous', urlencode(serialize($previous)));
     $p_form->addHTML($p_table->html());
     $p_form->addSubmit('', 'save-permissions', __('admin', 'save-changes'));
     return array(sprintf('%s: %s', __('admin', 'edit-group'), $g->getName()), $message . $p_form->html());
 }
Exemplo n.º 20
0
 public function action_index()
 {
     $id = (int) $this->request->param('id', 0);
     $page = ORM::factory('Page', $id);
     if (!$page->loaded()) {
         throw new HTTP_Exception_404('Page not found');
     }
     if ($page->static) {
         $content = $page->content->where('type', '=', 'static')->find();
         $this->redirect('manage/contents/show/' . $content);
     } else {
         $find_childs = ORM::factory('Page')->where('parent_id', '=', $id)->find_all()->as_array(null, 'id');
         if (count($find_childs) == 0) {
             $this->redirect('manage/contents/list/' . $id);
         } else {
             Message::error('В этот раздел нельзя добавлять содержимое.');
             $this->redirect('manage/pages');
         }
     }
 }
Exemplo n.º 21
0
 public function validate(Message $message = null)
 {
     $this->verror = [];
     foreach ($this->rules as $key => $rule) {
         $validators = $rule[0];
         $errormsg = isset($rule[1]) ? $rule[1] : null;
         foreach ($validators as $validator) {
             if (!$this->{$validator}($this->{$key})) {
                 if ($message) {
                     $message->error($errormsg);
                 }
                 $this->verror[$key] = $errormsg ? $errormsg : $this->errors[$validator];
                 break;
             }
         }
     }
     if ($this->verror) {
         throw new PostValidationException('Invalid post data');
     }
 }
Exemplo n.º 22
0
 public function action_close($id)
 {
     $project = ORM::factory('project', $id);
     if (!$project->loaded()) {
         Message::error('No Such Project');
         Request::instance()->redirect('project/');
     }
     if (Auth::instance()->get_user()->id != $project->user_id) {
         Message::error('That Project Doesn\'t Belong To You');
         Request::instance()->redirect('project/');
     }
     $project->closed = true;
     $project->save();
     if ($project->saved()) {
         Message::success('Closed project, ' . HTML::chars($project->name));
         Request::instance()->redirect('project/');
     } else {
         Message::error('Could not close project.');
         Request::instance()->redirect('project/view/' . $project->id);
     }
 }
Exemplo n.º 23
0
 public function action_delete($role_id = 0)
 {
     $this->auto_render = false;
     $role_id = intval($role_id);
     if ($role_id > 0) {
         $role = BLL_Role::getById($role_id);
         if ($role) {
             if (count($role->Users) == 0) {
                 $role->delete();
                 Message::success('Xóa nhóm thành công!');
             } else {
                 Message::error('Không thể xóa nhóm vì có chứa thành viên bên trong');
             }
         } else {
             Message::error('Không thể tìm thấy nhóm');
         }
     } else {
         Message::error('Không thể tìm thấy nhóm');
     }
     Request::instance()->redirect('/admin/role/index');
 }
Exemplo n.º 24
0
 public static function display()
 {
     $messages = "";
     if ($_POST['cc_form'] === 'add-user') {
         $username = $_POST['username'];
         $password = $_POST['password'];
         $cpassword = $_POST['confirm-password'];
         $group = $_POST['group'];
         if ($password != $cpassword) {
             $messages .= Message::error(__('admin', 'passwords-dont-match'));
         } else {
             $rows = Database::select('users', 'name', array('name = ? AND type = ?', $username, 'user'), null, 1)->fetch(PDO::FETCH_ASSOC);
             if (!empty($rows)) {
                 $messages .= Message::error(__('admin', 'username-in-use'));
             } else {
                 $hash = hash('whirlpool', $password);
                 $result = Database::insert('users', array('name' => filter('admin_add_user_username', $username), 'value' => $hash, 'type' => 'user', 'group' => filter('admin_add_group', $group), 'data' => serialize(filter('admin_add_user_data', array()))));
                 if ($result === 1) {
                     $messages .= Message::success(__('admin', 'user-added'));
                 }
             }
         }
     }
     $form = new Form('self', 'post', 'add-user');
     $groups = Users::allGroups();
     foreach ($groups as $key => $value) {
         $groups[$value->getId()] = $value->getName();
     }
     $form->startFieldset(__("admin", 'user-information'));
     $form->addInput(__('admin', 'username'), 'text', 'username', self::get('username'));
     $form->addInput(__('admin', 'password'), 'password', 'password');
     $form->addInput(__('admin', 'confirm-password'), 'password', 'confirm-password');
     $form->addSelectList(__('admin', 'group'), 'group', $groups, true, self::get('group'));
     plugin('admin_add_user_custom_fields', array(&$form));
     $form->addSubmit('', 'add-user', __('admin', 'add-user'));
     $form->endFieldset();
     plugin('admin_add_user_custom_fieldset', array(&$form));
     $form = $form->endAndGetHTML();
     return array(__('admin', 'add-user'), $messages . $form);
 }
 function saveEntry($arrData, $intEntryId = null)
 {
     global $_ARRAYLANG, $_CORELANG, $objDatabase, $_LANGID, $objInit;
     $objFWUser = \FWUser::getFWUserObject();
     $translationStatus = isset($arrData['translationStatus']) ? $arrData['translationStatus'] : array();
     //get data
     $intId = intval($intEntryId);
     $intFormId = intval($arrData['formId']);
     $strCreateDate = mktime();
     $strUpdateDate = mktime();
     $intUserId = intval($objFWUser->objUser->getId());
     $strLastIp = contrexx_addslashes($_SERVER['REMOTE_ADDR']);
     $strTransStatus = contrexx_addslashes(join(",", $translationStatus));
     //$arrCategories = explode(",",$arrData['selectedCategories']);
     //$arrLevels= explode("&",$arrData['selectedLevels']);
     if ($objInit->mode == 'backend') {
         $intReadyToConfirm = 1;
     } else {
         if ($this->arrSettings['settingsReadyToConfirm'] == 1) {
             $intReadyToConfirm = intval($arrData['readyToConfirm']);
         } else {
             $intReadyToConfirm = 1;
         }
     }
     switch ($this->arrSettings['settingsEntryDisplaydurationValueType']) {
         case 1:
             $intDiffDay = $this->arrSettings['settingsEntryDisplaydurationValue'];
             $intDiffMonth = 0;
             $intDiffYear = 0;
             break;
         case 2:
             $intDiffDay = 0;
             $intDiffMonth = $this->arrSettings['settingsEntryDisplaydurationValue'];
             $intDiffYear = 0;
             break;
         case 3:
             $intDiffDay = 0;
             $intDiffMonth = 0;
             $intDiffYear = $this->arrSettings['settingsEntryDisplaydurationValue'];
             break;
     }
     if (empty($intId)) {
         if ($objInit->mode == 'backend') {
             $intConfirmed = 1;
             $intActive = intval($arrData['status']) ? 1 : 0;
             $intShowIn = 3;
             $intDurationType = intval($arrData['durationType']);
             $intDurationStart = $this->dateFromInput($arrData['durationStart']);
             $intDurationEnd = $this->dateFromInput($arrData['durationEnd']);
         } else {
             $intConfirmed = $this->arrSettings['settingsConfirmNewEntries'] == 1 ? 0 : 1;
             $intActive = 1;
             $intShowIn = 2;
             $intDurationType = $this->arrSettings['settingsEntryDisplaydurationType'];
             $intDurationStart = mktime();
             $intDurationEnd = mktime(0, 0, 0, date("m") + $intDiffMonth, date("d") + $intDiffDay, date("Y") + $intDiffYear);
         }
         $strValidateDate = $intConfirmed == 1 ? mktime() : 0;
         //insert new entry
         $objResult = $objDatabase->Execute("\n                INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_entries\n                   SET `form_id`='" . $intFormId . "',\n                       `create_date`='" . $strCreateDate . "',\n                       `validate_date`='" . $strValidateDate . "',\n                       `update_date`='" . $strValidateDate . "',\n                       `added_by`='" . $intUserId . "',\n                       `lang_id`='" . $_LANGID . "',\n                       `hits`='0',\n                       `last_ip`='" . $strLastIp . "',\n                       `confirmed`='" . $intConfirmed . "',\n                       `active`='" . $intActive . "',\n                       `duration_type`='" . $intDurationType . "',\n                       `duration_start`='" . $intDurationStart . "',\n                       `duration_end`='" . $intDurationEnd . "',\n                       `duration_notification`='0',\n                       `translation_status`='" . $strTransStatus . "',\n                       `ready_to_confirm`='" . $intReadyToConfirm . "',\n                       `updated_by`=" . $intUserId . ",\n                       `popular_hits`=0,\n                       `popular_date`='" . $strValidateDate . "'");
         if (!$objResult) {
             return false;
         }
         $intId = $objDatabase->Insert_ID();
     } else {
         self::getEntries($intId);
         $intOldReadyToConfirm = $this->arrEntries[$intId]['entryReadyToConfirm'];
         if ($objInit->mode == 'backend') {
             $intConfirmed = 1;
             $intShowIn = 3;
             $intDurationStart = $this->dateFromInput($arrData['durationStart']);
             $intDurationEnd = $this->dateFromInput($arrData['durationEnd']);
             $arrAdditionalQuery[] = "`duration_type`='" . intval($arrData['durationType']) . "', `duration_start`='" . intval($intDurationStart) . "',  `duration_end`='" . intval($intDurationEnd) . "'";
             $arrAdditionalQuery[] = "`active`='" . (intval($arrData['status']) ? 1 : 0) . "'";
         } else {
             $intConfirmed = $this->arrSettings['settingsConfirmUpdatedEntries'] == 1 ? 0 : 1;
             $intShowIn = 2;
             $arrAdditionalQuery = null;
         }
         $arrAdditionalQuery[] = " `updated_by`='" . $intUserId . "'";
         if (intval($arrData['userId']) != 0) {
             $arrAdditionalQuery[] = "`added_by`='" . intval($arrData['userId']) . "'";
         }
         if (!empty($arrData['durationResetNotification'])) {
             $arrAdditionalQuery[] = "`duration_notification`='0'";
         }
         $strAdditionalQuery = join(",", $arrAdditionalQuery);
         $strValidateDate = $intConfirmed == 1 ? mktime() : 0;
         $objUpdateEntry = $objDatabase->Execute("\n                UPDATE " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_entries\n                   SET `update_date`='" . $strUpdateDate . "',\n                       `translation_status`='" . $strTransStatus . "',\n                       `ready_to_confirm`='" . $intReadyToConfirm . "',\n                       {$strAdditionalQuery}\n                 WHERE `id`='{$intId}'");
         if (!$objUpdateEntry) {
             return false;
         }
         $objDeleteCategories = $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_categories WHERE entry_id='" . $intId . "'");
         $objDeleteLevels = $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_levels WHERE entry_id='" . $intId . "'");
     }
     //////////////////////
     // STORE ATTRIBUTES //
     //////////////////////
     $error = false;
     foreach ($this->getInputfields() as $arrInputfield) {
         // store selected category (field = category)
         if ($arrInputfield['id'] == 1) {
             $selectedCategories = isset($arrData['selectedCategories']) ? $arrData['selectedCategories'] : array();
             foreach ($selectedCategories as $intCategoryId) {
                 $objResult = $objDatabase->Execute("\n                    INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_categories\n                       SET `entry_id`='" . intval($intId) . "',\n                           `category_id`='" . intval($intCategoryId) . "'");
                 if (!$objResult) {
                     \Message::error($objDatabase->ErrorMsg());
                     $error = true;
                 }
             }
             continue;
         }
         // store selected level (field = level)
         if ($arrInputfield['id'] == 2) {
             if ($this->arrSettings['settingsShowLevels'] == 1) {
                 $selectedLevels = isset($arrData['selectedLevels']) ? $arrData['selectedLevels'] : array();
                 foreach ($selectedLevels as $intLevelId) {
                     $objResult = $objDatabase->Execute("\n                        INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_levels\n                           SET `entry_id`='" . intval($intId) . "',\n                               `level_id`='" . intval($intLevelId) . "'");
                     if (!$objResult) {
                         \Message::error($objDatabase->ErrorMsg());
                         $error = true;
                     }
                 }
             }
             continue;
         }
         // skip meta attributes or ones that are out of scope (frontend/backend)
         if ($arrInputfield['type'] == 16 || $arrInputfield['type'] == 18 || $arrInputfield['type'] == 30 || $arrInputfield['show_in'] != $intShowIn && $arrInputfield['show_in'] != 1) {
             continue;
         }
         // truncate attribute's data ($arrInputfield) from database if it's VALUE is not set (empty) or set to it's default value
         if (empty($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']]) || $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']] == $arrInputfield['default_value'][$_LANGID]) {
             $objResult = $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields WHERE entry_id='" . $intId . "' AND field_id='" . intval($arrInputfield['id']) . "'");
             if (!$objResult) {
                 \Message::error($objDatabase->ErrorMsg());
                 $error = true;
             }
             continue;
         }
         // initialize attribute
         $strType = $arrInputfield['type_name'];
         $strInputfieldClass = "\\Cx\\Modules\\MediaDir\\Model\\Entity\\MediaDirectoryInputfield" . ucfirst($strType);
         try {
             $objInputfield = safeNew($strInputfieldClass, $this->moduleName);
         } catch (Exception $e) {
             \Message::error($e->getMessage());
             $error = true;
             continue;
         }
         // delete attribute's data of languages that are no longer in use
         $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields WHERE entry_id='" . $intId . "' AND field_id = '" . intval($arrInputfield['id']) . "' AND lang_id NOT IN (" . join(",", array_keys($this->arrFrontendLanguages)) . ")");
         // attribute is i18n
         foreach ($this->arrFrontendLanguages as $arrLang) {
             try {
                 $intLangId = $arrLang['id'];
                 // attribute is non-i18n
                 if ($arrInputfield['type_multi_lang'] == 0) {
                     $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']]);
                     $objResult = $objDatabase->Execute("\n                            INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields\n                               SET `entry_id`='" . intval($intId) . "',\n                                   `lang_id`='" . intval($intLangId) . "',\n                                   `form_id`='" . intval($intFormId) . "',\n                                   `field_id`='" . intval($arrInputfield['id']) . "',\n                                   `value`='" . contrexx_raw2db($strInputfieldValue) . "'\n                            ON DUPLICATE KEY\n                                UPDATE `value`='" . contrexx_raw2db($strInputfieldValue) . "'");
                     if (!$objResult) {
                         throw new \Exception($objDatabase->ErrorMsg());
                     }
                     continue;
                 }
                 // if the attribute is of type dynamic (meaning it can have an unlimited set of childs (references))
                 if ($arrInputfield['type_dynamic'] == 1) {
                     $arrDefault = array();
                     foreach ($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][0] as $intKey => $arrValues) {
                         $arrNewDefault = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$_LANGID][$intKey];
                         $arrOldDefault = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']]['old'][$intKey];
                         $arrNewValues = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId][$intKey];
                         foreach ($arrValues as $strKey => $strMasterValue) {
                             if ($intLangId == $_LANGID) {
                                 if ($arrNewDefault[$strKey] != $strMasterValue) {
                                     if ($strMasterValue != $arrOldDefault[$strKey] && $arrNewDefault[$strKey] == $arrOldDefault[$strKey]) {
                                         $arrDefault[$intKey][$strKey] = $strMasterValue;
                                     } else {
                                         $arrDefault[$intKey][$strKey] = $arrNewDefault[$strKey];
                                     }
                                 } else {
                                     $arrDefault[$intKey][$strKey] = $arrNewDefault[$strKey];
                                 }
                             } else {
                                 if ($arrNewValues[$strKey] == '') {
                                     $arrDefault[$intKey][$strKey] = $strMasterValue;
                                 } else {
                                     $arrDefault = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId];
                                 }
                             }
                         }
                         $strDefault = $arrDefault;
                     }
                     $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $strDefault, $intLangId);
                 } else {
                     if (empty($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId]) || $intLangId == $_LANGID) {
                         $strMaster = isset($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][0]) ? $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][0] : null;
                         $strNewDefault = isset($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$_LANGID]) ? $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$_LANGID] : '';
                         if ($strNewDefault != $strMaster) {
                             $strDefault = $strMaster;
                         } else {
                             $strDefault = isset($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId]) ? $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId] : '';
                         }
                         $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $strDefault, $intLangId);
                     } else {
                         // regular attribute get parsed
                         $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId], $intLangId);
                     }
                 }
                 $objResult = $objDatabase->Execute("\n                        INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields\n                           SET `entry_id`='" . intval($intId) . "',\n                               `lang_id`='" . intval($intLangId) . "',\n                               `form_id`='" . intval($intFormId) . "',\n                               `field_id`='" . intval($arrInputfield['id']) . "',\n                               `value`='" . contrexx_raw2db($strInputfieldValue) . "'\n                        ON DUPLICATE KEY\n                            UPDATE `value`='" . contrexx_raw2db($strInputfieldValue) . "'");
                 if (!$objResult) {
                     throw new \Exception($objDatabase->ErrorMsg());
                 }
             } catch (Exception $e) {
                 \Message::error($e->getMessage());
                 $error = true;
             }
         }
     }
     if (empty($intEntryId)) {
         if ($intReadyToConfirm == 1) {
             new MediaDirectoryMail(1, $intId, $this->moduleName);
         }
         new MediaDirectoryMail(2, $intId, $this->moduleName);
     } else {
         if ($intReadyToConfirm == 1 && $intOldReadyToConfirm == 0) {
             new MediaDirectoryMail(1, $intId, $this->moduleName);
         }
         new MediaDirectoryMail(6, $intId, $this->moduleName);
     }
     return $intId;
 }
Exemplo n.º 26
0
 /**
  * Sets criteria tables and columns
  *
  * @return void
  */
 private function _setCriteriaTablesAndColumns()
 {
     // The tables list sent by a previously submitted form
     if (PMA_isValid($_REQUEST['TableList'], 'array')) {
         foreach ($_REQUEST['TableList'] as $each_table) {
             $this->_criteriaTables[$each_table] = ' selected="selected"';
         }
     }
     // end if
     $all_tables = $GLOBALS['dbi']->query('SHOW TABLES FROM ' . Util::backquote($this->_db) . ';', null, DatabaseInterface::QUERY_STORE);
     $all_tables_count = $GLOBALS['dbi']->numRows($all_tables);
     if (0 == $all_tables_count) {
         Message::error(__('No tables found in database.'))->display();
         exit;
     }
     // The tables list gets from MySQL
     while (list($table) = $GLOBALS['dbi']->fetchRow($all_tables)) {
         $columns = $GLOBALS['dbi']->getColumns($this->_db, $table);
         if (empty($this->_criteriaTables[$table]) && !empty($_REQUEST['TableList'])) {
             $this->_criteriaTables[$table] = '';
         } else {
             $this->_criteriaTables[$table] = ' selected="selected"';
         }
         //  end if
         // The fields list per selected tables
         if ($this->_criteriaTables[$table] == ' selected="selected"') {
             $each_table = Util::backquote($table);
             $this->_columnNames[] = $each_table . '.*';
             foreach ($columns as $each_column) {
                 $each_column = $each_table . '.' . Util::backquote($each_column['Field']);
                 $this->_columnNames[] = $each_column;
                 // increase the width if necessary
                 $this->_form_column_width = max(mb_strlen($each_column), $this->_form_column_width);
             }
             // end foreach
         }
         // end if
     }
     // end while
     $GLOBALS['dbi']->freeResult($all_tables);
     // sets the largest width found
     $this->_realwidth = $this->_form_column_width . 'ex';
 }
Exemplo n.º 27
0
 public static function invalidIdError()
 {
     self::$invalid = true;
     return Message::error(__('admin', "edit-page-invalid-id"));
 }
Exemplo n.º 28
0
 public function action_delete()
 {
     $id = (int) $this->request->param('id', 0);
     $role = ORM::factory('role', $id);
     if (!$role->loaded()) {
         Message::error(__('Role: doesn\'t exists!'));
         Log::error('Attempt to access non-existent role.');
         $this->request->redirect(Route::get('admin/role')->uri());
     }
     $this->title = __('Delete :title', array(':title' => $role->name));
     $view = View::factory('form/confirm')->set('action', Route::url('admin/role', array('action' => 'delete', 'id' => $role->id)))->set('title', $role->name);
     // If deletion is not desired, redirect to list
     if (isset($_POST['no']) and $this->valid_post()) {
         $this->request->redirect(Route::get('admin/role')->uri());
     }
     // If deletion is confirmed
     if (isset($_POST['yes']) and $this->valid_post()) {
         try {
             $role->delete();
             //delete the role
             Message::success(__('Role: :name deleted successful!', array(':name' => $role->name)));
             $this->request->redirect(Route::get('admin/role')->uri());
         } catch (Exception $e) {
             Log::error('Error occured deleting role id: :id, :message', array(':id' => $role->id, ':message' => $e->getMessage()));
             Message::error('An error occured deleting blog, :post.', array(':post' => $post->title));
             $this->request->redirect(Route::get('admin/role')->uri());
         }
     }
     $this->response->body($view);
 }
Exemplo n.º 29
0
$send_count = 1;
$send_delay = 1;
//Delays the program execution for the given number of seconds.
ignore_user_abort(true);
// Ignore user aborts and allow the script to run forever
set_time_limit(300);
//to prevent the script from dying
foreach ($to_list as $row) {
    if ($send_count % $between_delay == 0) {
        sleep($send_delay);
        //Delays the program execution for the given number of seconds.
    }
    $address = $row;
    if (!empty($address)) {
        $mail->AddAddress($address, "User");
        $mail->Send();
        $mail->ClearAddresses();
        //clear address
    }
    $send_count++;
}
//print_r($mail->ErrorInfo);
//exit;
if (!empty($mail->ErrorInfo)) {
    Message::error($mail->ErrorInfo);
    if ($redirect != 'no') {
        $this->request->redirect(URL_BASE . $redirect);
    }
}
//$mail->AddAttachment("images/phpmailer.gif");      // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
 /**
  * Save recent/favorite tables into phpMyAdmin database.
  *
  * @return true|Message
  */
 public function saveToDb()
 {
     $username = $GLOBALS['cfg']['Server']['user'];
     $sql_query = " REPLACE INTO " . $this->_getPmaTable() . " (`username`, `tables`)" . " VALUES ('" . $username . "', '" . Util::sqlAddSlashes(json_encode($this->_tables)) . "')";
     $success = $GLOBALS['dbi']->tryQuery($sql_query, $GLOBALS['controllink']);
     if (!$success) {
         $error_msg = '';
         switch ($this->_tableType) {
             case 'recent':
                 $error_msg = __('Could not save recent table!');
                 break;
             case 'favorite':
                 $error_msg = __('Could not save favorite table!');
                 break;
         }
         $message = Message::error($error_msg);
         $message->addMessage('<br /><br />');
         $message->addMessage(Message::rawError($GLOBALS['dbi']->getError($GLOBALS['controllink'])));
         return $message;
     }
     return true;
 }