Example #1
0
 /**
  * __construct
  *
  * Class constructor, appends Module settings to default settings
  *
  */
 public function __construct()
 {
     $this->setSettings(__CLASS__, parse_ini_file(strtolower(__CLASS__) . '.ini.php', true));
     //set the plugin link and the icon for the menubar
     self::$name = "Alerts";
     self::$icon = "fa-file";
 }
Example #2
0
 public static function newInstance()
 {
     if (!self::$instance instanceof self) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Example #3
0
 function doModel()
 {
     switch ($this->action) {
         case 'change_email_confirm':
             //change email confirm
             if (Params::getParam('userId') && Params::getParam('code')) {
                 $userManager = new User();
                 $user = $userManager->findByPrimaryKey(Params::getParam('userId'));
                 if ($user['s_pass_code'] == Params::getParam('code') && $user['b_enabled'] == 1) {
                     $userEmailTmp = UserEmailTmp::newInstance()->findByPk(Params::getParam('userId'));
                     $code = osc_genRandomPassword(50);
                     $userManager->update(array('s_email' => $userEmailTmp['s_new_email']), array('pk_i_id' => $userEmailTmp['fk_i_user_id']));
                     Item::newInstance()->update(array('s_contact_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     ItemComment::newInstance()->update(array('s_author_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     Alerts::newInstance()->update(array('s_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     Session::newInstance()->_set('userEmail', $userEmailTmp['s_new_email']);
                     UserEmailTmp::newInstance()->delete(array('s_new_email' => $userEmailTmp['s_new_email']));
                     osc_add_flash_ok_message(_m('Your email has been changed successfully'));
                     $this->redirectTo(osc_user_profile_url());
                 } else {
                     osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                     $this->redirectTo(osc_base_url());
                 }
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'activate_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $result = 0;
             if ($email != '' && $secret != '') {
                 $result = Alerts::newInstance()->activate($email, $secret);
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Alert activated'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to activate alert. Please contact the administrator'));
             }
             $this->redirectTo(osc_base_url(true));
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             if ($email != '' && $secret != '') {
                 Alerts::newInstance()->delete(array('s_email' => $email, 'S_secret' => $secret));
                 osc_add_flash_ok_message(_m('Unsubscribed correctly'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to unsubscribe you. Please contact the administrator'));
             }
             $this->redirectTo(osc_base_url());
             break;
         default:
             $this->redirectTo(osc_user_login_url());
             break;
     }
 }
Example #4
0
 public function recentAlarmsAck()
 {
     if (($id = Request::get('fldModJackAlertID')) == '' || ($alert = Alerts::get($id)) === false) {
         return $this->index() . Widget::popupWrapper('Invalid Alert ID');
     }
     $alert->status = Alerts::STATUS_SEEN;
     $alert->save();
     return $this->index() . Widget::popupWrapper("Acknowledged Alert {$alert->id} - {$alert->desc}");
 }
Example #5
0
function osc_runAlert($type = null, $last_exec = null)
{
    if (!in_array($type, array('HOURLY', 'DAILY', 'WEEKLY', 'INSTANT'))) {
        return;
    }
    if ($last_exec == null) {
        $cron = Cron::newInstance()->getCronByType($type);
        if (is_array($cron)) {
            $last_exec = $cron['d_last_exec'];
        } else {
            $last_exec = '0000-00-00 00:00:00';
        }
    }
    $internal_name = 'alert_email_hourly';
    switch ($type) {
        case 'HOURLY':
            $internal_name = 'alert_email_hourly';
            break;
        case 'DAILY':
            $internal_name = 'alert_email_daily';
            break;
        case 'WEEKLY':
            $internal_name = 'alert_email_weekly';
            break;
        case 'INSTANT':
            $internal_name = 'alert_email_instant';
            break;
    }
    $active = TRUE;
    $searches = Alerts::newInstance()->findByTypeGroup($type, $active);
    foreach ($searches as $s_search) {
        // Get if there're new ads on this search
        $json = $s_search['s_search'];
        $array_conditions = (array) json_decode($json);
        $new_search = Search::newInstance();
        $new_search->setJsonAlert($array_conditions);
        $new_search->addConditions(sprintf(" %st_item.dt_pub_date > '%s' ", DB_TABLE_PREFIX, $last_exec));
        $items = $new_search->doSearch();
        $totalItems = $new_search->count();
        if (count($items) > 0) {
            // If we have new items from last check
            // Catch the user subscribed to this search
            $users = Alerts::newInstance()->findUsersBySearchAndType($s_search['s_search'], $type, $active);
            if (count($users) > 0) {
                $ads = '';
                foreach ($items as $item) {
                    $ads .= '<a href="' . osc_item_url_ns($item['pk_i_id']) . '">' . $item['s_title'] . '</a><br/>';
                }
                foreach ($users as $user) {
                    osc_run_hook('hook_' . $internal_name, $user, $ads, $s_search, $items, $totalItems);
                    AlertsStats::newInstance()->increase(date('Y-m-d'));
                }
            }
        }
    }
}
Example #6
0
 public function table($params)
 {
     $this->addTableHeader();
     $this->getDBParams($params);
     $alerts = Alerts::newInstance()->search($this->start, $this->limit, $this->order_by['column_name'], $this->order_by['type'], $this->search);
     $this->processData($alerts);
     $this->total = $alerts['total_results'];
     $this->total_filtered = $alerts['rows'];
     return $this->getData();
 }
Example #7
0
 function __construct()
 {
     header('Content-Type: application/json');
     require_once 'libs/config.php';
     //Archivo con configuraciones.
     $this->_system = System::singleton();
     //contiene objeto system
     $_POST = json_decode(file_get_contents('php://input'), true);
     require_once 'libs/apps/alerts/class.alerts.php';
     $alerts = new Alerts();
     $what = empty($_POST['what']) ? null : $_POST['what'];
     $token = empty($_POST['token']) ? null : $_POST['token'];
     if ($token === session_id()) {
         if ($what === "LIST_ALERTS") {
             $period = empty($_POST['period']) ? null : $_POST['period'];
             $type = empty($_POST['type']) ? null : $_POST['type'];
             $data = array('period' => $period, 'type' => $type);
             $current_alerts = $alerts->listAlerts($data);
             echo json_encode($current_alerts);
         }
     } else {
         echo json_encode(array("status" => "Failed", "message" => "Cross site injection detected", "code" => 501));
     }
 }
Example #8
0
function customFrmText()
{
    $user = __get('user');
    $return = array();
    if (isset($user['pk_i_id'])) {
        $return['edit'] = true;
        $return['title'] = __('Edit user');
        $return['action_frm'] = 'edit_post';
        $return['btn_text'] = __('Update user');
        $return['alerts'] = Alerts::newInstance()->findByUser($user['pk_i_id'], true);
    } else {
        $return['edit'] = false;
        $return['title'] = __('Add new user');
        $return['action_frm'] = 'create_post';
        $return['btn_text'] = __('Add new user');
        $return['alerts'] = array();
    }
    return $return;
}
Example #9
0
 function edit($userId)
 {
     $input = $this->prepareData(false);
     $this->manager->update($input, array('pk_i_id' => $userId));
     if ($this->is_admin) {
         Item::newInstance()->update(array('s_contact_name' => $input['s_name'], 's_contact_email' => $input['s_email']), array('fk_i_user_id' => $userId));
         ItemComment::newInstance()->update(array('s_author_name' => $input['s_name'], 's_author_email' => $input['s_email']), array('fk_i_user_id' => $userId));
         Alerts::newInstance()->update(array('s_email' => $input['s_email']), array('fk_i_user_id' => $userId));
         Log::newInstance()->insertLog('user', 'edit', $userId, $input['s_email'], $this->is_admin ? 'admin' : 'user', $this->is_admin ? osc_logged_admin_id() : osc_logged_user_id());
     } else {
         Item::newInstance()->update(array('s_contact_name' => $input['s_name']), array('fk_i_user_id' => $userId));
         ItemComment::newInstance()->update(array('s_author_name' => $input['s_name']), array('fk_i_user_id' => $userId));
         $user = $this->manager->findByPrimaryKey($userId);
         Log::newInstance()->insertLog('user', 'edit', $userId, $user['s_email'], $this->is_admin ? 'admin' : 'user', $this->is_admin ? osc_logged_admin_id() : osc_logged_user_id());
     }
     Session::newInstance()->_set('userName', $input['s_name']);
     $phone = $input['s_phone_mobile'] ? $input['s_phone_mobile'] : $input['s_phone_land'];
     Session::newInstance()->_set('userPhone', $phone);
     if (is_array(Params::getParam('s_info'))) {
         foreach (Params::getParam('s_info') as $key => $value) {
             $this->manager->updateDescription($userId, $key, $value);
         }
     }
     osc_run_hook('user_edit_completed', $userId);
     if ($this->is_admin) {
         $iUpdated = 0;
         if (Params::getParam("b_enabled") != '' && Params::getParam("b_enabled") == 1) {
             $iUpdated += $this->manager->update(array('b_enabled' => 1), array('pk_i_id' => $userId));
         } else {
             $iUpdated += $this->manager->update(array('b_enabled' => 0), array('pk_i_id' => $userId));
         }
         if (Params::getParam("b_active") != '' && Params::getParam("b_active") == 1) {
             $iUpdated += $this->manager->update(array('b_active' => 1), array('pk_i_id' => $userId));
         } else {
             $iUpdated += $this->manager->update(array('b_active' => 0), array('pk_i_id' => $userId));
         }
         if ($iUpdated > 0) {
             return 2;
         }
     }
     return 0;
 }
Example #10
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->findByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->findByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'location_countries':
             // This is the autocomplete AJAX
             $countries = Country::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($countries);
             break;
         case 'location_regions':
             // This is the autocomplete AJAX
             $regions = Region::newInstance()->ajax(Params::getParam("term"), Params::getParam("country"));
             echo json_encode($regions);
             break;
         case 'location_cities':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"), Params::getParam("region"));
             echo json_encode($cities);
             break;
         case 'delete_image':
             // Delete images via AJAX
             $id = Params::getParam('id');
             $item = Params::getParam('item');
             $code = Params::getParam('code');
             $secret = Params::getParam('secret');
             $json = array();
             if (Session::newInstance()->_get('userId') != '') {
                 $userId = Session::newInstance()->_get('userId');
                 $user = User::newInstance()->findByPrimaryKey($userId);
             } else {
                 $userId = null;
                 $user = null;
             }
             // Check for required fields
             if (!(is_numeric($id) && is_numeric($item) && preg_match('/^([a-z0-9]+)$/i', $code))) {
                 $json['success'] = false;
                 $json['msg'] = _m("The selected photo couldn't be deleted, the url doesn't exist");
                 echo json_encode($json);
                 return false;
             }
             $aItem = Item::newInstance()->findByPrimaryKey($item);
             // Check if the item exists
             if (count($aItem) == 0) {
                 $json['success'] = false;
                 $json['msg'] = _m('The item doesn\'t exist');
                 echo json_encode($json);
                 return false;
             }
             // Check if the item belong to the user
             if ($userId != null && $userId != $aItem['fk_i_user_id']) {
                 $json['success'] = false;
                 $json['msg'] = _m('The item doesn\'t belong to you');
                 echo json_encode($json);
                 return false;
             }
             // Check if the secret passphrase match with the item
             if ($userId == null && $aItem['fk_i_user_id'] == null && $secret != $aItem['s_secret']) {
                 $json['success'] = false;
                 $json['msg'] = _m('The item doesn\'t belong to you');
                 echo json_encode($json);
                 return false;
             }
             // Does id & code combination exist?
             $result = ItemResource::newInstance()->existResource($id, $code);
             if ($result > 0) {
                 // Delete: file, db table entry
                 osc_deleteResource($id);
                 ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $item, 's_name' => $code));
                 $json['msg'] = _m('The selected photo has been successfully deleted');
                 $json['success'] = 'true';
             } else {
                 $json['msg'] = _m("The selected photo couldn't be deleted");
                 $json['success'] = 'false';
             }
             echo json_encode($json);
             return true;
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $alert = Params::getParam("alert");
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if ($alert != '' && $email != '') {
                 if (preg_match("/^[_a-z0-9-+]+(\\.[_a-z0-9-+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})\$/", $email)) {
                     $secret = osc_genRandomPassword();
                     if (Alerts::newInstance()->createAlert($userid, $email, $alert, $secret)) {
                         if ((int) $userid > 0) {
                             $user = User::newInstance()->findByPrimaryKey($userid);
                             if ($user['b_active'] == 1 && $user['b_enabled'] == 1) {
                                 Alerts::newInstance()->activate($email, $secret);
                                 echo '1';
                                 return true;
                             } else {
                                 echo '-1';
                                 return false;
                             }
                         } else {
                             osc_run_hook('hook_email_alert_validation', $alert, $email, $secret);
                         }
                         echo "1";
                     } else {
                         echo "0";
                     }
                     return true;
                 } else {
                     echo '-1';
                     return false;
                 }
             }
             echo '0';
             return false;
             break;
         case 'runhook':
             //Run hooks
             $hook = Params::getParam("hook");
             switch ($hook) {
                 case 'item_form':
                     $catId = Params::getParam("catId");
                     if ($catId != '') {
                         osc_run_hook("item_form", $catId);
                     } else {
                         osc_run_hook("item_form");
                     }
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     if ($hook == '') {
                         return false;
                     } else {
                         osc_run_hook($hook);
                     }
                     break;
             }
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxfile = Params::getParam("ajaxfile");
             if ($ajaxfile != '') {
                 require_once osc_plugins_path() . $ajaxfile;
             } else {
                 echo json_encode(array('error' => __('no action defined')));
             }
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Example #11
0
 function doModel()
 {
     switch ($this->action) {
         case 'change_email_confirm':
             //change email confirm
             if (Params::getParam('userId') && Params::getParam('code')) {
                 $userManager = new User();
                 $user = $userManager->findByPrimaryKey(Params::getParam('userId'));
                 if ($user['s_pass_code'] == Params::getParam('code') && $user['b_enabled'] == 1) {
                     $userEmailTmp = UserEmailTmp::newInstance()->findByPk(Params::getParam('userId'));
                     $code = osc_genRandomPassword(50);
                     $userManager->update(array('s_email' => $userEmailTmp['s_new_email']), array('pk_i_id' => $userEmailTmp['fk_i_user_id']));
                     Item::newInstance()->update(array('s_contact_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     ItemComment::newInstance()->update(array('s_author_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     Alerts::newInstance()->update(array('s_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     Session::newInstance()->_set('userEmail', $userEmailTmp['s_new_email']);
                     UserEmailTmp::newInstance()->delete(array('s_new_email' => $userEmailTmp['s_new_email']));
                     osc_add_flash_ok_message(_m('Your email has been changed successfully'));
                     $this->redirectTo(osc_user_profile_url());
                 } else {
                     osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                     $this->redirectTo(osc_base_url());
                 }
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'activate_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $result = 0;
             if ($email != '' && $secret != '') {
                 $result = Alerts::newInstance()->activate($email, $secret);
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Alert activated'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to activate alert. Please contact the administrator'));
             }
             $this->redirectTo(osc_base_url(true));
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             if ($email != '' && $secret != '') {
                 Alerts::newInstance()->delete(array('s_email' => $email, 'S_secret' => $secret));
                 osc_add_flash_ok_message(_m('Unsubscribed correctly'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to unsubscribe you. Please contact the administrator'));
             }
             $this->redirectTo(osc_base_url());
             break;
         case 'pub_profile':
             $userID = Params::getParam('id');
             $user = User::newInstance()->findByPrimaryKey($userID);
             // user doesn't exist
             if (!$user) {
                 $this->redirectTo(osc_base_url());
             }
             View::newInstance()->_exportVariableToView('user', $user);
             $items = Item::newInstance()->findByUserIDEnabled($user['pk_i_id'], 0, 3);
             View::newInstance()->_exportVariableToView('items', $items);
             $this->doView('user-public-profile.php');
             break;
         case 'contact_post':
             $user = User::newInstance()->findByPrimaryKey(Params::getParam('id'));
             View::newInstance()->_exportVariableToView('user', $user);
             if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     Session::newInstance()->_setForm("yourEmail", Params::getParam('yourEmail'));
                     Session::newInstance()->_setForm("yourName", Params::getParam('yourName'));
                     Session::newInstance()->_setForm("phoneNumber", Params::getParam('phoneNumber'));
                     Session::newInstance()->_setForm("message_body", Params::getParam('message'));
                     $this->redirectTo(osc_user_public_profile_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             osc_run_hook('hook_email_contact_user', Params::getParam('id'), Params::getParam('yourEmail'), Params::getParam('yourName'), Params::getParam('phoneNumber'), Params::getParam('message'));
             $this->redirectTo(osc_user_public_profile_url());
             break;
         default:
             $this->redirectTo(osc_user_login_url());
             break;
     }
 }
Example #12
0
 function doModel()
 {
     switch ($this->action) {
         case 'dashboard':
             //dashboard...
             $max_items = Params::getParam('max_items') != '' ? Params::getParam('max_items') : 5;
             $aItems = Item::newInstance()->findByUserIDEnabled(osc_logged_user_id(), 0, $max_items);
             //calling the view...
             $this->_exportVariableToView('items', $aItems);
             $this->_exportVariableToView('max_items', $max_items);
             $this->doView('user-dashboard.php');
             break;
         case 'profile':
             //profile...
             $user = User::newInstance()->findByPrimaryKey(osc_logged_user_id());
             $aCountries = Country::newInstance()->listAll();
             $aRegions = array();
             if ($user['fk_c_country_code'] != '') {
                 $aRegions = Region::newInstance()->findByCountry($user['fk_c_country_code']);
             } elseif (count($aCountries) > 0) {
                 $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
             }
             $aCities = array();
             if ($user['fk_i_region_id'] != '') {
                 $aCities = City::newInstance()->findByRegion($user['fk_i_region_id']);
             } else {
                 if (count($aRegions) > 0) {
                     $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
                 }
             }
             //calling the view...
             $this->_exportVariableToView('countries', $aCountries);
             $this->_exportVariableToView('regions', $aRegions);
             $this->_exportVariableToView('cities', $aCities);
             $this->_exportVariableToView('user', $user);
             $this->_exportVariableToView('locales', OSCLocale::newInstance()->listAllEnabled());
             $this->doView('user-profile.php');
             break;
         case 'profile_post':
             //profile post...
             osc_csrf_check();
             $userId = Session::newInstance()->_get('userId');
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(false);
             $success = $userActions->edit($userId);
             if ($success == 1 || $success == 2) {
                 osc_add_flash_ok_message(_m('Your profile has been updated successfully'));
             } else {
                 osc_add_flash_error_message($success);
             }
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'alerts':
             //alerts
             $aAlerts = Alerts::newInstance()->findByUser(Session::newInstance()->_get('userId'), false);
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             foreach ($aAlerts as $k => $a) {
                 $array_conditions = (array) json_decode($a['s_search']);
                 //                                            $search = Search::newInstance();
                 $search = new Search();
                 $search->setJsonAlert($array_conditions);
                 $search->limit(0, 3);
                 $aAlerts[$k]['items'] = $search->doSearch();
             }
             $this->_exportVariableToView('alerts', $aAlerts);
             View::newInstance()->_reset('alerts');
             $this->_exportVariableToView('user', $user);
             $this->doView('user-alerts.php');
             break;
         case 'change_email':
             //change email
             $this->doView('user-change_email.php');
             break;
         case 'change_email_post':
             //change email post
             osc_csrf_check();
             if (!osc_validate_email(Params::getParam('new_email'))) {
                 osc_add_flash_error_message(_m('The specified e-mail is not valid'));
                 $this->redirectTo(osc_change_user_email_url());
             } else {
                 $user = User::newInstance()->findByEmail(Params::getParam('new_email'));
                 if (!isset($user['pk_i_id'])) {
                     $userEmailTmp = array();
                     $userEmailTmp['fk_i_user_id'] = Session::newInstance()->_get('userId');
                     $userEmailTmp['s_new_email'] = Params::getParam('new_email');
                     UserEmailTmp::newInstance()->insertOrUpdate($userEmailTmp);
                     $code = osc_genRandomPassword(30);
                     $date = date('Y-m-d H:i:s');
                     $userManager = new User();
                     $userManager->update(array('s_pass_code' => $code, 's_pass_date' => $date, 's_pass_ip' => $_SERVER['REMOTE_ADDR']), array('pk_i_id' => Session::newInstance()->_get('userId')));
                     $validation_url = osc_change_user_email_confirm_url(Session::newInstance()->_get('userId'), $code);
                     osc_run_hook('hook_email_new_email', Params::getParam('new_email'), $validation_url);
                     $this->redirectTo(osc_user_profile_url());
                 } else {
                     osc_add_flash_error_message(_m('The specified e-mail is already in use'));
                     $this->redirectTo(osc_change_user_email_url());
                 }
             }
             break;
         case 'change_username':
             //change username
             $this->doView('user-change_username.php');
             break;
         case 'change_username_post':
             //change username
             $username = osc_sanitize_username(Params::getParam('s_username'));
             osc_run_hook('before_username_change', Session::newInstance()->_get('userId'), $username);
             if ($username != '') {
                 $user = User::newInstance()->findByUsername($username);
                 if (isset($user['s_username'])) {
                     osc_add_flash_error_message(_m('The specified username is already in use'));
                 } else {
                     if (!osc_is_username_blacklisted($username)) {
                         User::newInstance()->update(array('s_username' => $username), array('pk_i_id' => Session::newInstance()->_get('userId')));
                         osc_add_flash_ok_message(_m('The username was updated'));
                         osc_run_hook('after_username_change', Session::newInstance()->_get('userId'), Params::getParam('s_username'));
                         $this->redirectTo(osc_user_profile_url());
                     } else {
                         osc_add_flash_error_message(_m('The specified username is not valid, it contains some invalid words'));
                     }
                 }
             } else {
                 osc_add_flash_error_message(_m('The specified username could not be empty'));
             }
             $this->redirectTo(osc_change_user_username_url());
             break;
         case 'change_password':
             //change password
             $this->doView('user-change_password.php');
             break;
         case 'change_password_post':
             //change password post
             osc_csrf_check();
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             if (Params::getParam('password', false, false) == '' || Params::getParam('new_password', false, false) == '' || Params::getParam('new_password2', false, false) == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (!osc_verify_password(Params::getParam('password', false, false), $user['s_password'])) {
                 osc_add_flash_error_message(_m("Current password doesn't match"));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (!Params::getParam('new_password', false, false)) {
                 osc_add_flash_error_message(_m("Passwords can't be empty"));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (Params::getParam('new_password', false, false) != Params::getParam('new_password2', false, false)) {
                 osc_add_flash_error_message(_m("Passwords don't match"));
                 $this->redirectTo(osc_change_user_password_url());
             }
             User::newInstance()->update(array('s_password' => osc_hash_password(Params::getParam('new_password', false, false))), array('pk_i_id' => Session::newInstance()->_get('userId')));
             osc_add_flash_ok_message(_m('Password has been changed'));
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'items':
             // view items user
             $itemsPerPage = Params::getParam('itemsPerPage') != '' ? Params::getParam('itemsPerPage') : 10;
             $page = Params::getParam('iPage') > 0 ? Params::getParam('iPage') - 1 : 0;
             $itemType = Params::getParam('itemType');
             $total_items = Item::newInstance()->countItemTypesByUserID(osc_logged_user_id(), $itemType);
             $total_pages = ceil($total_items / $itemsPerPage);
             $items = Item::newInstance()->findItemTypesByUserID(osc_logged_user_id(), $page * $itemsPerPage, $itemsPerPage, $itemType);
             $this->_exportVariableToView('items', $items);
             $this->_exportVariableToView('search_total_pages', $total_pages);
             $this->_exportVariableToView('search_total_items', $total_items);
             $this->_exportVariableToView('items_per_page', $itemsPerPage);
             $this->_exportVariableToView('items_type', $itemType);
             $this->_exportVariableToView('search_page', $page);
             $this->doView('user-items.php');
             break;
         case 'activate_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $result = 0;
             if ($email != '' && $secret != '') {
                 $result = Alerts::newInstance()->activate($email, $secret);
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Alert activated'));
             } else {
                 osc_add_flash_error_message(_m('Oops! There was a problem trying to activate your alert. Please contact an administrator'));
             }
             $this->redirectTo(osc_base_url());
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $alert = Alerts::newInstance()->findByPrimaryKey($id);
             $result = 0;
             if (!empty($alert)) {
                 if ($email == $alert['s_email'] && $secret == $alert['s_secret']) {
                     $result = Alerts::newInstance()->unsub($id);
                 }
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Unsubscribed correctly'));
             } else {
                 osc_add_flash_error_message(_m('Oops! There was a problem trying to unsubscribe you. Please contact an administrator'));
             }
             $this->redirectTo(osc_user_alerts_url());
             break;
         case 'delete':
             $id = Params::getParam('id');
             $secret = Params::getParam('secret');
             if (osc_is_web_user_logged_in()) {
                 $user = User::newInstance()->findByPrimaryKey(osc_logged_user_id());
                 View::newInstance()->_exportVariableToView('user', $user);
                 if (!empty($user) && osc_logged_user_id() == $id && $secret == $user['s_secret']) {
                     User::newInstance()->deleteUser(osc_logged_user_id());
                     Session::newInstance()->_drop('userId');
                     Session::newInstance()->_drop('userName');
                     Session::newInstance()->_drop('userEmail');
                     Session::newInstance()->_drop('userPhone');
                     Cookie::newInstance()->pop('oc_userId');
                     Cookie::newInstance()->pop('oc_userSecret');
                     Cookie::newInstance()->set();
                     osc_add_flash_ok_message(_m("Your account have been deleted"));
                     $this->redirectTo(osc_base_url());
                 } else {
                     osc_add_flash_error_message(_m("Oops! you can not do that"));
                     $this->redirectTo(osc_user_dashboard_url());
                 }
             } else {
                 osc_add_flash_error_message(_m("Oops! you can not do that"));
                 $this->redirectTo(osc_base_url());
             }
             break;
     }
 }
Example #13
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->getByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->getByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $alert = Params::getParam("alert");
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if ($alert != '' && $email != '') {
                 if (preg_match("/^[_a-z0-9-+]+(\\.[_a-z0-9-+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})\$/", $email)) {
                     Alerts::newInstance()->createAlert($userid, $email, $alert);
                     echo "1";
                 } else {
                     echo '0';
                 }
                 return true;
             }
             echo '0';
             return false;
             break;
         case 'runhook':
             //Run hooks
             $hook = Params::getParam("hook");
             switch ($hook) {
                 case 'item_form':
                     $catId = Params::getParam("catId");
                     if ($catId != '') {
                         osc_run_hook("item_form", $catId);
                     } else {
                         osc_run_hook("item_form");
                     }
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     if ($hook == '') {
                         return false;
                     } else {
                         osc_run_hook($hook);
                     }
                     break;
             }
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxfile = Params::getParam("ajaxfile");
             if ($ajaxfile != '') {
                 require_once osc_plugins_path() . $ajaxfile;
             } else {
                 echo json_encode(array('error' => __('no action defined')));
             }
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
 }
Example #14
0
/**
 * Convert alerts < 2.4, updating s_search with json encoded to based64.
 *
 * @param string $alert base64+serialized
 */
function convertAlert($alert)
{
    // decode search model
    $data = base64_decode($alert['s_search']);
    if (is_serialized($data)) {
        // don't attempt to unserialize data that wasn't serialized going in
        $data = unserialize($data);
        // if search model, convert alert
        if (get_class($data) == 'Search') {
            // get json
            $json = $data->toJson(true);
            // insert new alert with json
            $aCondition = array('s_email' => $alert['s_email'], 'b_active' => $alert['b_active'], 'e_type' => $alert['e_type']);
            if ($alert['fk_i_user_id'] != '') {
                $aCondition['fk_i_user_id'] = (int) $alert['fk_i_user_id'];
            }
            if ($alert['s_secret'] != '') {
                $aCondition['s_secret'] = $alert['s_secret'];
            }
            Alerts::newInstance()->update(array('s_search' => base64_encode($json)), $aCondition);
        }
    }
}
Example #15
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'create':
             // calling create view
             $aRegions = array();
             $aCities = array();
             $aCountries = Country::newInstance()->listAll();
             if (isset($aCountries[0]['pk_c_code'])) {
                 $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
             }
             if (isset($aRegions[0]['pk_i_id'])) {
                 $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
             }
             $this->_exportVariableToView('user', null);
             $this->_exportVariableToView('countries', $aCountries);
             $this->_exportVariableToView('regions', $aRegions);
             $this->_exportVariableToView('cities', $aCities);
             $this->_exportVariableToView('locales', OSCLocale::newInstance()->listAllEnabled());
             $this->doView("users/frm.php");
             break;
         case 'create_post':
             // creating the user...
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(true);
             $success = $userActions->add();
             switch ($success) {
                 case 1:
                     osc_add_flash_ok_message(_m("The user has been created. We've sent an activation e-mail"), 'admin');
                     break;
                 case 2:
                     osc_add_flash_ok_message(_m('The user has been created successfully'), 'admin');
                     break;
                 default:
                     osc_add_flash_error_message($success, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'edit':
             // calling the edit view
             $aUser = $this->userManager->findByPrimaryKey(Params::getParam("id"));
             $aCountries = Country::newInstance()->listAll();
             $aRegions = array();
             if ($aUser['fk_c_country_code'] != '') {
                 $aRegions = Region::newInstance()->findByCountry($aUser['fk_c_country_code']);
             } else {
                 if (count($aCountries) > 0) {
                     $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
                 }
             }
             $aCities = array();
             if ($aUser['fk_i_region_id'] != '') {
                 $aCities = City::newInstance()->findByRegion($aUser['fk_i_region_id']);
             } else {
                 if (count($aRegions) > 0) {
                     $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
                 }
             }
             $csrf_token = osc_csrf_token_url();
             if ($aUser['b_active']) {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=users&action=deactivate&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=INACTIVE">' . __('Deactivate') . '</a>';
             } else {
                 $actions[] = '<a class="btn btn-red float-left" href="' . osc_admin_base_url(true) . '?page=users&action=activate&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=ACTIVE">' . __('Activate') . '</a>';
             }
             if ($aUser['b_enabled']) {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=users&action=disable&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=DISABLE">' . __('Block') . '</a>';
             } else {
                 $actions[] = '<a class="btn btn-red float-left" href="' . osc_admin_base_url(true) . '?page=users&action=enable&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=ENABLE">' . __('Unblock') . '</a>';
             }
             $this->_exportVariableToView("actions", $actions);
             $this->_exportVariableToView("user", $aUser);
             $this->_exportVariableToView("countries", $aCountries);
             $this->_exportVariableToView("regions", $aRegions);
             $this->_exportVariableToView("cities", $aCities);
             $this->_exportVariableToView("locales", OSCLocale::newInstance()->listAllEnabled());
             $this->doView("users/frm.php");
             break;
         case 'edit_post':
             // edit post
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(true);
             $success = $userActions->edit(Params::getParam("id"));
             if ($success == 1) {
                 osc_add_flash_ok_message(_m('The user has been updated'), 'admin');
             } else {
                 if ($success == 2) {
                     osc_add_flash_ok_message(_m('The user has been updated and activated'), 'admin');
                 } else {
                     osc_add_flash_error_message($success);
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('id'));
                 }
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'resend_activation':
             //activate
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->resend_activation($id);
             }
             if ($iUpdated == 0) {
                 osc_add_flash_error_message(_m('No users have been selected'), 'admin');
             } else {
                 osc_add_flash_ok_message(sprintf(_mn('Activation email sent to one user', 'Activation email sent to %s users', $iUpdated), $iUpdated), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'activate':
             //activate
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->activate($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been activated');
             } else {
                 $msg = sprintf(_mn('One user has been activated', '%s users have been activated', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'deactivate':
             //deactivate
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->deactivate($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been deactivated');
             } else {
                 $msg = sprintf(_mn('One user has been deactivated', '%s users have been deactivated', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'enable':
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->enable($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been enabled');
             } else {
                 $msg = sprintf(_mn('One user has been unblocked', '%s users have been unblocked', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'disable':
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->disable($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been disabled');
             } else {
                 $msg = sprintf(_mn('One user has been blocked', '%s users have been blocked', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'delete':
             //delete
             osc_csrf_check();
             $iDeleted = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             foreach ($userId as $id) {
                 $user = $this->userManager->findByPrimaryKey($id);
                 Log::newInstance()->insertLog('user', 'delete', $id, $user['s_email'], 'admin', osc_logged_admin_id());
                 if ($this->userManager->deleteUser($id)) {
                     $iDeleted++;
                 }
             }
             if ($iDeleted == 0) {
                 $msg = _m('No users have been deleted');
             } else {
                 $msg = sprintf(_mn('One user has been deleted', '%s users have been deleted', $iDeleted), $iDeleted);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'delete_alerts':
             //delete
             $iDeleted = 0;
             $alertId = Params::getParam('alert_id');
             if (!is_array($alertId)) {
                 osc_add_flash_error_message(_m("Alert id isn't in the correct format"), 'admin');
                 if (Params::getParam('user_id') == '') {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
                 } else {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
                 }
             }
             $mAlerts = new Alerts();
             foreach ($alertId as $id) {
                 Log::newInstance()->insertLog('user', 'delete_alerts', $id, $id, 'admin', osc_logged_admin_id());
                 $iDeleted += $mAlerts->delete(array('pk_i_id' => $id));
             }
             if ($iDeleted == 0) {
                 $msg = _m('No alerts have been deleted');
             } else {
                 $msg = sprintf(_mn('One alert has been deleted', '%s alerts have been deleted', $iDeleted), $iDeleted);
             }
             osc_add_flash_ok_message($msg, 'admin');
             if (Params::getParam('user_id') == '') {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
             } else {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
             }
             break;
         case 'status_alerts':
             //delete
             $status = Params::getParam("status");
             $iUpdated = 0;
             $alertId = Params::getParam('alert_id');
             if (!is_array($alertId)) {
                 osc_add_flash_error_message(_m("Alert id isn't in the correct format"), 'admin');
                 if (Params::getParam('user_id') == '') {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
                 } else {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
                 }
             }
             $mAlerts = new Alerts();
             foreach ($alertId as $id) {
                 if ($status == 1) {
                     $iUpdated += $mAlerts->activate($id);
                 } else {
                     $iUpdated += $mAlerts->deactivate($id);
                 }
             }
             if ($status == 1) {
                 if ($iUpdated == 0) {
                     $msg = _m('No alerts have been activated');
                 } else {
                     $msg = sprintf(_mn('One alert has been activated', '%s alerts have been activated', $iUpdated), $iUpdated);
                 }
             } else {
                 if ($iUpdated == 0) {
                     $msg = _m('No alerts have been deactivated');
                 } else {
                     $msg = sprintf(_mn('One alert has been deactivated', '%s alerts have been deactivated', $iUpdated), $iUpdated);
                 }
             }
             osc_add_flash_ok_message($msg, 'admin');
             if (Params::getParam('user_id') == '') {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
             } else {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
             }
             break;
         case 'settings':
             // calling the users settings view
             $this->doView('users/settings.php');
             break;
         case 'settings_post':
             // updating users
             osc_csrf_check();
             $iUpdated = 0;
             $enabledUserValidation = Params::getParam('enabled_user_validation');
             $enabledUserValidation = $enabledUserValidation != '' ? true : false;
             $enabledUserRegistration = Params::getParam('enabled_user_registration');
             $enabledUserRegistration = $enabledUserRegistration != '' ? true : false;
             $enabledUsers = Params::getParam('enabled_users');
             $enabledUsers = $enabledUsers != '' ? true : false;
             $notifyNewUser = Params::getParam('notify_new_user');
             $notifyNewUser = $notifyNewUser != '' ? true : false;
             $usernameBlacklistTmp = explode(",", Params::getParam('username_blacklist'));
             foreach ($usernameBlacklistTmp as $k => $v) {
                 $usernameBlacklistTmp[$k] = strtolower(trim($v));
             }
             $usernameBlacklist = implode(",", $usernameBlacklistTmp);
             $iUpdated += osc_set_preference('enabled_user_validation', $enabledUserValidation);
             $iUpdated += osc_set_preference('enabled_user_registration', $enabledUserRegistration);
             $iUpdated += osc_set_preference('enabled_users', $enabledUsers);
             $iUpdated += osc_set_preference('notify_new_user', $notifyNewUser);
             $iUpdated += osc_set_preference('username_blacklist', $usernameBlacklist);
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(_m("User settings have been updated"), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=settings');
             break;
         case 'alerts':
             // manage alerts view
             require_once osc_lib_path() . "osclass/classes/datatables/AlertsDataTable.php";
             // set default iDisplayLength
             if (Params::getParam('iDisplayLength') != '') {
                 Cookie::newInstance()->push('listing_iDisplayLength', Params::getParam('iDisplayLength'));
                 Cookie::newInstance()->set();
             } else {
                 // set a default value if it's set in the cookie
                 if (Cookie::newInstance()->get_value('listing_iDisplayLength') != '') {
                     Params::setParam('iDisplayLength', Cookie::newInstance()->get_value('listing_iDisplayLength'));
                 } else {
                     Params::setParam('iDisplayLength', 10);
                 }
             }
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             // Table header order by related
             if (Params::getParam('sort') == '') {
                 Params::setParam('sort', 'date');
             }
             if (Params::getParam('direction') == '') {
                 Params::setParam('direction', 'desc');
             }
             $page = (int) Params::getParam('iPage');
             if ($page == 0) {
                 $page = 1;
             }
             Params::setParam('iPage', $page);
             $params = Params::getParamsAsArray();
             $alertsDataTable = new AlertsDataTable();
             $alertsDataTable->table($params);
             $aData = $alertsDataTable->getData();
             if (count($aData['aRows']) == 0 && $page != 1) {
                 $total = (int) $aData['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $aData['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aData', $aData);
             $this->_exportVariableToView('aRawRows', $alertsDataTable->rawRows());
             $this->doView("users/alerts.php");
             break;
         case 'ban':
             // manage ban rules view
             if (Params::getParam("action") != "") {
                 osc_run_hook("ban_rules_bulk_" . Params::getParam("action"), Params::getParam('id'));
             }
             require_once osc_lib_path() . "osclass/classes/datatables/BanRulesDataTable.php";
             // set default iDisplayLength
             if (Params::getParam('iDisplayLength') != '') {
                 Cookie::newInstance()->push('listing_iDisplayLength', Params::getParam('iDisplayLength'));
                 Cookie::newInstance()->set();
             } else {
                 // set a default value if it's set in the cookie
                 if (Cookie::newInstance()->get_value('listing_iDisplayLength') != '') {
                     Params::setParam('iDisplayLength', Cookie::newInstance()->get_value('listing_iDisplayLength'));
                 } else {
                     Params::setParam('iDisplayLength', 10);
                 }
             }
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             // Table header order by related
             if (Params::getParam('sort') == '') {
                 Params::setParam('sort', 'date');
             }
             if (Params::getParam('direction') == '') {
                 Params::setParam('direction', 'desc');
             }
             $page = (int) Params::getParam('iPage');
             if ($page == 0) {
                 $page = 1;
             }
             Params::setParam('iPage', $page);
             $params = Params::getParamsAsArray();
             $banRulesDataTable = new BanRulesDataTable();
             $banRulesDataTable->table($params);
             $aData = $banRulesDataTable->getData();
             if (count($aData['aRows']) == 0 && $page != 1) {
                 $total = (int) $aData['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $aData['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aData', $aData);
             $this->_exportVariableToView('aRawRows', $banRulesDataTable->rawRows());
             $bulk_options = array(array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')), array('value' => 'delete_ban_rule', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected ban rules?'), strtolower(__('Delete'))), 'label' => __('Delete')));
             $bulk_options = osc_apply_filter("ban_rule_bulk_filter", $bulk_options);
             $this->_exportVariableToView('bulk_options', $bulk_options);
             //calling the view...
             $this->doView('users/ban.php');
             break;
         case 'edit_ban_rule':
             $this->_exportVariableToView('rule', BanRule::newInstance()->findByPrimaryKey(Params::getParam('id')));
             $this->doView('users/ban_frm.php');
             break;
         case 'edit_ban_rule_post':
             osc_csrf_check();
             if (Params::getParam('s_ip') == '' && Params::getParam('s_email') == '') {
                 osc_add_flash_warning_message(_m("Both rules can not be empty"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             }
             BanRule::newInstance()->update(array('s_name' => Params::getParam('s_name'), 's_ip' => Params::getParam('s_ip'), 's_email' => strtolower(Params::getParam('s_email'))), array('pk_i_id' => Params::getParam('id')));
             osc_add_flash_ok_message(_m('Rule updated correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             break;
         case 'create_ban_rule':
             $this->_exportVariableToView('rule', null);
             $this->doView('users/ban_frm.php');
             break;
         case 'create_ban_rule_post':
             osc_csrf_check();
             if (Params::getParam('s_ip') == '' && Params::getParam('s_email') == '') {
                 osc_add_flash_warning_message(_m("Both rules can not be empty"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             }
             BanRule::newInstance()->insert(array('s_name' => Params::getParam('s_name'), 's_ip' => Params::getParam('s_ip'), 's_email' => strtolower(Params::getParam('s_email'))));
             osc_add_flash_ok_message(_m('Rule saved correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             break;
         case 'delete_ban_rule':
             //delete ban rules
             osc_csrf_check();
             $iDeleted = 0;
             $ruleId = Params::getParam('id');
             if (!is_array($ruleId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             }
             $ruleMgr = BanRule::newInstance();
             foreach ($ruleId as $id) {
                 if ($ruleMgr->deleteByPrimaryKey($id)) {
                     $iDeleted++;
                 }
             }
             if ($iDeleted == 0) {
                 $msg = _m('No rules have been deleted');
             } else {
                 $msg = sprintf(_mn('One ban rule has been deleted', '%s ban rules have been deleted', $iDeleted), $iDeleted);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             break;
         default:
             // manage users view
             if (Params::getParam("action") != "") {
                 osc_run_hook("user_bulk_" . Params::getParam("action"), Params::getParam('id'));
             }
             require_once osc_lib_path() . "osclass/classes/datatables/UsersDataTable.php";
             // set default iDisplayLength
             if (Params::getParam('iDisplayLength') != '') {
                 Cookie::newInstance()->push('listing_iDisplayLength', Params::getParam('iDisplayLength'));
                 Cookie::newInstance()->set();
             } else {
                 // set a default value if it's set in the cookie
                 if (Cookie::newInstance()->get_value('listing_iDisplayLength') != '') {
                     Params::setParam('iDisplayLength', Cookie::newInstance()->get_value('listing_iDisplayLength'));
                 } else {
                     Params::setParam('iDisplayLength', 10);
                 }
             }
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             // Table header order by related
             if (Params::getParam('sort') == '') {
                 Params::setParam('sort', 'date');
             }
             if (Params::getParam('direction') == '') {
                 Params::setParam('direction', 'desc');
             }
             $page = (int) Params::getParam('iPage');
             if ($page == 0) {
                 $page = 1;
             }
             Params::setParam('iPage', $page);
             $params = Params::getParamsAsArray();
             $usersDataTable = new UsersDataTable();
             $usersDataTable->table($params);
             $aData = $usersDataTable->getData();
             if (count($aData['aRows']) == 0 && $page != 1) {
                 $total = (int) $aData['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $aData['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aData', $aData);
             $this->_exportVariableToView('withFilters', $usersDataTable->withFilters());
             $this->_exportVariableToView('aRawRows', $usersDataTable->rawRows());
             $bulk_options = array(array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')), array('value' => 'activate', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Activate'))), 'label' => __('Activate')), array('value' => 'deactivate', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Deactivate'))), 'label' => __('Deactivate')), array('value' => 'enable', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Unblock'))), 'label' => __('Unblock')), array('value' => 'disable', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Block'))), 'label' => __('Block')), array('value' => 'delete', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Delete'))), 'label' => __('Delete')));
             if (osc_user_validation_enabled()) {
                 $bulk_options[] = array('value' => 'resend_activation', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Resend the activation to'))), 'label' => __('Resend activation'));
             }
             $bulk_options = osc_apply_filter("user_bulk_filter", $bulk_options);
             $this->_exportVariableToView('bulk_options', $bulk_options);
             //calling the view...
             $this->doView('users/index.php');
             break;
     }
 }
Example #16
0
        function edit($userId)
        {

            $input = $this->prepareData(false);

            // hook pre add or edit
            osc_run_hook('pre_user_post');
            $flash_error = '';
            $error = array();
            if($this->is_admin) {
                $user_email = $this->manager->findByEmail($input['s_email']);
                if(isset($user_email['pk_i_id']) && $user_email['pk_i_id']!=$userId) {
                    $flash_error .= sprintf(_m('The specified e-mail is already used by %s') , $user_email['s_username']) . PHP_EOL;
                    $error[] = 3;
                }
            }

            if($input['s_name']=='') {
                $flash_error .= _m('The name cannot be empty').PHP_EOL;
                $error[] = 10;
            }

            if($this->is_admin){
                if( Params::getParam('s_password', false, false) != Params::getParam('s_password2', false, false) ) {
                    $flash_error .= _m("Passwords don't match") . PHP_EOL;
                    $error[] = 7;
                }
            }

            if($flash_error!='') {
                return $flash_error;
            }

            $this->manager->update($input, array('pk_i_id' => $userId));

            if($this->is_admin) {
                Item::newInstance()->update( array('s_contact_name' => $input['s_name'], 's_contact_email' => $input['s_email']), array('fk_i_user_id' => $userId) );
                ItemComment::newInstance()->update( array('s_author_name' => $input['s_name'], 's_author_email' => $input['s_email']), array('fk_i_user_id' => $userId) );
                Alerts::newInstance()->update( array('s_email' => $input['s_email']), array('fk_i_user_id' => $userId) );

                Log::newInstance()->insertLog( 'user', 'edit', $userId, $input['s_email'], $this->is_admin ? 'admin' : 'user', $this->is_admin ? osc_logged_admin_id() : osc_logged_user_id() );
            } else {
                Item::newInstance()->update( array('s_contact_name' => $input['s_name']), array('fk_i_user_id' => $userId) );
                ItemComment::newInstance()->update( array('s_author_name' => $input['s_name']), array('fk_i_user_id' => $userId) );
                $user = $this->manager->findByPrimaryKey($userId);

                Log::newInstance()->insertLog('user', 'edit', $userId, $user['s_email'], $this->is_admin ? 'admin' : 'user', $this->is_admin ? osc_logged_admin_id() : osc_logged_user_id() );
            }

            if(!$this->is_admin) {
                Session::newInstance()->_set('userName', $input['s_name']);
                $phone = ($input['s_phone_mobile'])? $input['s_phone_mobile'] : $input['s_phone_land'];
                Session::newInstance()->_set('userPhone', $phone);
            }

            if ( is_array( Params::getParam('s_info') ) ) {
                foreach (Params::getParam('s_info') as $key => $value) {
                    $this->manager->updateDescription($userId, $key, $value);
                }
            }

            osc_run_hook('user_edit_completed', $userId);

            if ( $this->is_admin ) {
                $iUpdated = 0;
                if( (Params::getParam("b_enabled") != '') && (Params::getParam("b_enabled") == 1 ) ) {
                    $iUpdated += $this->manager->update( array('b_enabled' => 1), array('pk_i_id' => $userId) );
                } else {
                    $iUpdated += $this->manager->update( array('b_enabled' => 0), array('pk_i_id' => $userId) );
                }

                if( (Params::getParam("b_active") != '') && (Params::getParam("b_active") == 1) ) {
                    $iUpdated += $this->manager->update( array('b_active' => 1), array('pk_i_id' => $userId) );
                } else {
                    $iUpdated += $this->manager->update( array('b_active' => 0), array('pk_i_id' => $userId) );
                }

                if($iUpdated > 0) {
                    return 2;
                }
            }

            return 1;
        }
 public function postAlertsList()
 {
     $query = Alerts::where('pid', '=', Session::get('pid'))->where('alert_date_active', '<=', date('Y-m-d H:i:s', time() + 1209600))->where('alert_date_complete', '=', '0000-00-00 00:00:00')->where('alert_reason_not_complete', '=', '')->where('practice_id', '=', Session::get('practice_id'))->get();
     $result = '';
     if ($query) {
         $result .= '<ul>';
         foreach ($query as $row) {
             $result .= '<li>' . $row->alert . ' (Due ' . date('m/d/Y', $this->human_to_unix($row->alert_date_active)) . ') - ' . $row->alert_description . '</li>';
         }
         $result .= '</ul>';
     } else {
         $result .= ' None.';
     }
     echo $result;
 }
Example #18
0
 function doModel()
 {
     switch ($this->action) {
         case 'change_email_confirm':
             //change email confirm
             if (Params::getParam('userId') && Params::getParam('code')) {
                 $userManager = new User();
                 $user = $userManager->findByPrimaryKey(Params::getParam('userId'));
                 if ($user['s_pass_code'] == Params::getParam('code') && $user['b_enabled'] == 1) {
                     $userEmailTmp = UserEmailTmp::newInstance()->findByPrimaryKey(Params::getParam('userId'));
                     $code = osc_genRandomPassword(50);
                     $userManager->update(array('s_email' => $userEmailTmp['s_new_email']), array('pk_i_id' => $userEmailTmp['fk_i_user_id']));
                     Item::newInstance()->update(array('s_contact_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     ItemComment::newInstance()->update(array('s_author_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     Alerts::newInstance()->update(array('s_email' => $userEmailTmp['s_new_email']), array('fk_i_user_id' => $userEmailTmp['fk_i_user_id']));
                     Session::newInstance()->_set('userEmail', $userEmailTmp['s_new_email']);
                     UserEmailTmp::newInstance()->delete(array('s_new_email' => $userEmailTmp['s_new_email']));
                     osc_add_flash_ok_message(_m('Your email has been changed successfully'));
                     $this->redirectTo(osc_user_profile_url());
                 } else {
                     osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                     $this->redirectTo(osc_base_url());
                 }
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'activate_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $alert = Alerts::newInstance()->findByPrimaryKey($id);
             $result = 0;
             if (!empty($alert)) {
                 if ($email == $alert['s_email'] && $secret == $alert['s_secret']) {
                     $user = User::newInstance()->findByEmail($alert['s_email']);
                     if (isset($user['pk_i_id'])) {
                         Alerts::newInstance()->update(array('fk_i_user_id' => $user['pk_i_id']), array('pk_i_id' => $id));
                     }
                     $result = Alerts::newInstance()->activate($id);
                 }
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Alert activated'));
             } else {
                 osc_add_flash_error_message(_m('Oops! There was a problem trying to activate your alert. Please contact an administrator'));
             }
             $this->redirectTo(osc_base_url());
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $alert = Alerts::newInstance()->findByPrimaryKey($id);
             $result = 0;
             if (!empty($alert)) {
                 if ($email == $alert['s_email'] && $secret == $alert['s_secret']) {
                     $result = Alerts::newInstance()->unsub($id);
                 }
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Unsubscribed correctly'));
             } else {
                 osc_add_flash_error_message(_m('Oops! There was a problem trying to unsubscribe you. Please contact an administrator'));
             }
             $this->redirectTo(osc_base_url());
             break;
         case 'pub_profile':
             if (Params::getParam('username') != '') {
                 $user = User::newInstance()->findByUsername(Params::getParam('username'));
             } else {
                 $user = User::newInstance()->findByPrimaryKey(Params::getParam('id'));
             }
             // user doesn't exist, show 404 error
             if (!$user) {
                 $this->do404();
                 return;
             }
             $itemsPerPage = Params::getParam('itemsPerPage') != '' ? Params::getParam('itemsPerPage') : 10;
             $page = Params::getParam('iPage') > 0 ? Params::getParam('iPage') - 1 : 0;
             $total_items = Item::newInstance()->countItemTypesByUserID($user['pk_i_id'], 'active');
             if ($itemsPerPage == 'all') {
                 $total_pages = 1;
                 $items = Item::newInstance()->findItemTypesByUserID($user['pk_i_id'], 0, null, 'active');
             } else {
                 $total_pages = ceil($total_items / $itemsPerPage);
                 $items = Item::newInstance()->findItemTypesByUserID($user['pk_i_id'], $page * $itemsPerPage, $itemsPerPage, 'active');
             }
             View::newInstance()->_exportVariableToView('user', $user);
             $this->_exportVariableToView('items', $items);
             $this->_exportVariableToView('search_total_pages', $total_pages);
             $this->_exportVariableToView('search_total_items', $total_items);
             $this->_exportVariableToView('items_per_page', $itemsPerPage);
             $this->_exportVariableToView('search_page', $page);
             $this->_exportVariableToView('canonical', osc_user_public_profile_url());
             $this->doView('user-public-profile.php');
             break;
         case 'contact_post':
             $user = User::newInstance()->findByPrimaryKey(Params::getParam('id'));
             View::newInstance()->_exportVariableToView('user', $user);
             if (osc_recaptcha_private_key() != '') {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     Session::newInstance()->_setForm("yourEmail", Params::getParam('yourEmail'));
                     Session::newInstance()->_setForm("yourName", Params::getParam('yourName'));
                     Session::newInstance()->_setForm("phoneNumber", Params::getParam('phoneNumber'));
                     Session::newInstance()->_setForm("message_body", Params::getParam('message'));
                     $this->redirectTo(osc_user_public_profile_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             $banned = osc_is_banned(Params::getParam('yourEmail'));
             if ($banned == 1) {
                 osc_add_flash_error_message(_m('Your current email is not allowed'));
                 $this->redirectTo(osc_user_public_profile_url());
             } else {
                 if ($banned == 2) {
                     osc_add_flash_error_message(_m('Your current IP is not allowed'));
                     $this->redirectTo(osc_user_public_profile_url());
                 }
             }
             osc_run_hook('hook_email_contact_user', Params::getParam('id'), Params::getParam('yourEmail'), Params::getParam('yourName'), Params::getParam('phoneNumber'), Params::getParam('message'));
             osc_add_flash_ok_message(_m('Your email has been sent properly.'));
             $this->redirectTo(osc_user_public_profile_url());
             break;
         default:
             $this->redirectTo(osc_user_login_url());
             break;
     }
 }
Example #19
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->getByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->getByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $alert = Params::getParam("alert");
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if ($alert != '' && $email != '') {
                 Alerts::newInstance()->insert(array('fk_i_user_id' => $userid, 's_email' => $email, 's_search' => $alert, 'e_type' => 'DAILY'));
                 echo "1";
                 return true;
             }
             echo '0';
             break;
         case 'runhook':
             //Run hooks
             $hook = Params::getParam("hook");
             switch ($hook) {
                 case 'item_form':
                     $catId = Params::getParam("catId");
                     if ($catId != '') {
                         osc_run_hook("item_form", $catId);
                     } else {
                         osc_run_hook("item_form");
                     }
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     if ($hook == '') {
                         return false;
                     } else {
                         osc_run_hook($hook);
                     }
                     break;
             }
             break;
         case 'items':
             // Return items (use external file oc-admin/ajax/item_processing.php)
             require_once osc_admin_base_path() . 'ajax/items_processing.php';
             $items_processing = new items_processing_ajax(Params::getParamsAsArray("get"));
             break;
         case 'media':
             // Return items (use external file oc-admin/ajax/media_processing.php)
             require_once osc_admin_base_path() . 'ajax/media_processing.php';
             $media_processing = new media_processing_ajax(Params::getParamsAsArray("get"));
             break;
         case 'categories_order':
             // Save the order of the categories
             $aIds = Params::getParam('list');
             $orderParent = 0;
             $orderSub = 0;
             $catParent = 0;
             $catManager = Category::newInstance();
             foreach ($aIds as $id => $parent) {
                 if ($parent == 'root') {
                     if (!$catManager->update_order($id, $orderParent)) {
                         $error = 1;
                     }
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = DB_CONST_NULL;
                     if (!$catManager->update($array, $conditions) > 0) {
                         $error = 1;
                     }
                     $orderParent++;
                 } else {
                     if ($parent != $catParent) {
                         $catParent = $parent;
                         $orderSub = 0;
                     }
                     if (!$catManager->update_order($id, $orderSub)) {
                         $error = 1;
                     }
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = $catParent;
                     if (!$catManager->update($array, $conditions) > 0) {
                         $error = 1;
                     }
                     $orderSub++;
                 }
             }
             $result = "{";
             $error = 0;
             if ($error) {
                 $result .= '"error" : "' . __("Some error ocurred") . '"';
             } else {
                 $result .= '"ok" : "' . __("Order saved") . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'category_edit_iframe':
             $this->_exportVariableToView("category", Category::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView("languages", OSCLocale::newInstance()->listAllEnabled());
             $this->doView("categories/iframe.php");
             break;
         case 'field_categories_iframe':
             $selected = Field::newInstance()->categories(Params::getParam("id"));
             if ($selected == null) {
                 $selected = array();
             }
             $this->_exportVariableToView("selected", $selected);
             $this->_exportVariableToView("field", Field::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll());
             $this->doView("fields/iframe.php");
             break;
         case 'field_categories_post':
             $error = 0;
             if (!$error) {
                 try {
                     $field = Field::newInstance()->findByName(Params::getParam("s_name"));
                     if (!isset($field['pk_i_id']) || isset($field['pk_i_id']) && $field['pk_i_id'] == Params::getParam("id")) {
                         Field::newInstance()->cleanCategoriesFromField(Params::getParam("id"));
                         $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("id");
                         $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug)));
                         Field::newInstance()->update(array('s_name' => Params::getParam("s_name"), 'e_type' => Params::getParam("field_type"), 's_slug' => $slug, 'b_required' => Params::getParam("field_required") == "1" ? 1 : 0, 's_options' => Params::getParam('s_options')), array('pk_i_id' => Params::getParam("id")));
                         Field::newInstance()->insertCategories(Params::getParam("id"), Params::getParam("categories"));
                     } else {
                         $error = 1;
                         $message = __("Sorry, you already have one field with that name");
                     }
                 } catch (Exception $e) {
                     $error = 1;
                     $message = __("Error while updating.");
                 }
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "' . __("Saved") . '", "text" : "' . Params::getParam("s_name") . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'delete_field':
             $id = Params::getParam("id");
             $error = 0;
             try {
                 $fieldManager = Field::newInstance();
                 $fieldManager->deleteByPrimaryKey($id);
                 $message = __('The custom field have been deleted');
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "Saved." ';
             }
             $result .= "}";
             echo $result;
             break;
         case 'enable_category':
             $id = Params::getParam("id");
             $enabled = Params::getParam("enabled") != '' ? Params::getParam("enabled") : 0;
             $error = 0;
             $aUpdated = "";
             try {
                 if ($id != '') {
                     $categoryManager = Category::newInstance();
                     $categoryManager->update(array('b_enabled' => $enabled), array('pk_i_id' => $id));
                     if ($enabled == 1) {
                         $msg = __('The category has been enabled');
                     } else {
                         $msg = __('The category has been disabled');
                     }
                     $categoryManager->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id));
                     $aUpdated = $categoryManager->listWhere("fk_i_parent_id = {$id}");
                     if ($enabled == 1) {
                         $msg .= "<br>" . __('The subcategories has been enabled');
                     } else {
                         $msg .= "<br>" . __('The subcategories has been disabled');
                     }
                 } else {
                     $error = 1;
                     $msg = __('There was a problem with this page. The ID for the category hasn\'t been set');
                 }
                 $message = $msg;
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error: %s') . " " . $e->getMessage();
             }
             $result = "{";
             $error = 0;
             if ($error) {
                 $result .= '"error" : "' . $message . '"';
             } else {
                 $result .= '"ok" : "' . $message . '"';
                 if (count($aUpdated) > 0) {
                     $result .= ', "afectedIds": [';
                     foreach ($aUpdated as $category) {
                         $result .= '{ "id" : "' . $category['pk_i_id'] . '" },';
                     }
                     $result = substr($result, 0, -1);
                     $result .= ']';
                 } else {
                     $result .= ', "afectedIds": []';
                 }
             }
             $result .= "}";
             echo $result;
             break;
         case 'delete_category':
             $id = Params::getParam("id");
             $error = 0;
             try {
                 $categoryManager = Category::newInstance();
                 $categoryManager->deleteByPrimaryKey($id);
                 $message = __('The categories have been deleted');
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "Saved." ';
             }
             $result .= "}";
             echo $result;
             break;
         case 'edit_category_post':
             $id = Params::getParam("id");
             $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0;
             $error = 0;
             $postParams = Params::getParamsAsArray();
             foreach ($postParams as $k => $v) {
                 if (preg_match('|(.+?)#(.+)|', $k, $m)) {
                     if ($m[2] == 's_name') {
                         if ($v != "") {
                             $aFieldsDescription[$m[1]][$m[2]] = $v;
                         } else {
                             $error = 1;
                             $message = __("All titles are required");
                         }
                     } else {
                         $aFieldsDescription[$m[1]][$m[2]] = $v;
                     }
                 }
             }
             $l = osc_language();
             if (!$error) {
                 try {
                     $categoryManager = Category::newInstance();
                     $categoryManager->updateByPrimaryKey($fields, $aFieldsDescription, $id);
                 } catch (Exception $e) {
                     $error = 1;
                     $message = __("Error while updating.");
                 }
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "' . __("Saved") . '", "text" : "' . $aFieldsDescription[$l]['s_name'] . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxfile = Params::getParam("ajaxfile");
             if ($ajaxfile != '') {
                 require_once osc_admin_base_path() . $ajaxfile;
             } else {
                 echo json_encode(array('error' => __('no action defined')));
             }
             break;
         case 'test_mail':
             $title = __('Test email') . ", " . osc_page_title();
             $body = __("Test email") . "<br><br>" . osc_page_title();
             $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body);
             $array = array();
             if (osc_sendMail($emailParams)) {
                 $array = array('status' => '1', 'html' => __('Email sent successfully'));
             } else {
                 $array = array('status' => '0', 'html' => __('An error has occurred while sending email'));
             }
             echo json_encode($array);
             break;
         case 'order_pages':
             $order = Params::getParam("order");
             $id = Params::getParam("id");
             $count = osc_count_static_pages();
             if ($order != '' && $id != '') {
                 $mPages = Page::newInstance();
                 $actual_page = $mPages->findByPrimaryKey($id);
                 $actual_order = $actual_page['i_order'];
                 $array = array();
                 $condition = array();
                 $new_order = $actual_order;
                 if ($order == 'up') {
                     if ($actual_order > 0) {
                         $new_order = $actual_order - 1;
                     }
                 } else {
                     if ($order == 'down') {
                         if ($actual_order != $count - 1) {
                             $new_order = $actual_order + 1;
                         }
                     }
                 }
                 if ($new_order != $actual_order) {
                     $auxpage = $mPages->findByOrder($new_order);
                     $array = array('i_order' => $actual_order);
                     $conditions = array('pk_i_id' => $auxpage['pk_i_id']);
                     $mPages->update($array, $conditions);
                     $array = array('i_order' => $new_order);
                     $conditions = array('pk_i_id' => $id);
                     $mPages->update($array, $conditions);
                 } else {
                 }
                 // json for datatables
                 $prefLocale = osc_current_admin_locale();
                 $aPages = $mPages->listAll(0);
                 $json = "[";
                 foreach ($aPages as $key => $page) {
                     $body = array();
                     if (isset($page['locale'][$prefLocale]) && !empty($page['locale'][$prefLocale]['s_title'])) {
                         $body = $page['locale'][$prefLocale];
                     } else {
                         $body = current($page['locale']);
                     }
                     $p_body = str_replace("'", "\\'", trim(strip_tags($body['s_title']), "\"'"));
                     $json .= "[\"<input type='checkbox' name='id[]' value='" . $page['pk_i_id'] . "' />\",";
                     $json .= "\"" . $page['s_internal_name'] . "<div id='datatables_quick_edit'>";
                     $json .= "<a href='" . osc_static_page_url() . "'>" . __('View page') . "</a> | ";
                     $json .= "<a href='" . osc_admin_base_url(true) . "?page=pages&action=edit&id=" . $page['pk_i_id'] . "'>";
                     $json .= __('Edit') . "</a>";
                     if (!$page['b_indelible']) {
                         $json .= " | ";
                         $json .= "<a onclick=\\\"javascript:return confirm('";
                         $json .= __('This action can\\\\\'t be undone. Are you sure you want to continue?') . "')\\\" ";
                         $json .= " href='" . osc_admin_base_url(true) . "?page=pages&action=delete&id=" . $page['pk_i_id'] . "'>";
                         $json .= __('Delete') . "</a>";
                     }
                     $json .= "</div>\",";
                     $json .= "\"" . $p_body . "\",";
                     $json .= "\"<img id='up' onclick='order_up(" . $page['pk_i_id'] . ");' style='cursor:pointer;width:15;height:15px;' src='" . osc_current_admin_theme_url('images/arrow_up.png') . "'/> <br/> <img id='down' onclick='order_down(" . $page['pk_i_id'] . ");' style='cursor:pointer;width:15;height:15px;' src='" . osc_current_admin_theme_url('images/arrow_down.png') . "'/>\"]";
                     if ($key != count($aPages) - 1) {
                         $json .= ',';
                     } else {
                         $json .= '';
                     }
                 }
                 $json .= "]";
                 echo $json;
             }
             break;
             /******************************
              ** COMPLETE UPGRADE PROCESS **
              ******************************/
         /******************************
          ** COMPLETE UPGRADE PROCESS **
          ******************************/
         case 'upgrade':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             $message = "";
             $error = 0;
             $remove_error_msg = "";
             $sql_error_msg = "";
             $rm_errors = 0;
             $perms = osc_save_permissions();
             osc_change_permissions();
             $maintenance_file = ABS_PATH . '.maintenance';
             $fileHandler = @fopen($maintenance_file, 'w');
             fclose($fileHandler);
             /***********************
              **** DOWNLOAD FILE ****
              ***********************/
             if (Params::getParam('file') != '') {
                 $tmp = explode("/", Params::getParam('file'));
                 $filename = end($tmp);
                 $result = osc_downloadFile(Params::getParam('file'), $filename);
                 if ($result) {
                     // Everything is OK, continue
                     /**********************
                      ***** UNZIP FILE *****
                      **********************/
                     @mkdir(ABS_PATH . 'oc-temp', 0777);
                     $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/');
                     if ($res == 1) {
                         // Everything is OK, continue
                         /**********************
                          ***** COPY FILES *****
                          **********************/
                         $fail = -1;
                         if ($handle = opendir(ABS_PATH . 'oc-temp')) {
                             $fail = 0;
                             while (false !== ($_file = readdir($handle))) {
                                 if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') {
                                     $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file);
                                     if ($data == false) {
                                         $fail = 1;
                                     }
                                 }
                             }
                             closedir($handle);
                             if ($fail == 0) {
                                 // Everything is OK, continue
                                 /**********************
                                  **** REMOVE FILES ****
                                  **********************/
                                 if (file_exists(ABS_PATH . 'oc-temp/remove.list')) {
                                     $lines = file(ABS_PATH . 'oc-temp/remove.list', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                                     foreach ($lines as $line_num => $r_file) {
                                         $unlink = @unlink(ABS_PATH . $r_file);
                                         if (!$unlink) {
                                             $remove_error_msg .= sprintf(__('Error removing file: %s'), $r_file) . "<br/>";
                                         }
                                     }
                                 }
                                 // Removing files is not important for the rest of the proccess
                                 // We will inform the user of the problems but the upgrade could continue
                                 /************************
                                  *** UPGRADE DATABASE ***
                                  ************************/
                                 $error_queries = array();
                                 if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) {
                                     $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql');
                                     $conn = getConnection();
                                     $error_queries = $conn->osc_updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql));
                                 }
                                 if ($error_queries[0]) {
                                     // Everything is OK, continue
                                     /**********************************
                                      ** EXECUTING ADDITIONAL ACTIONS **
                                      **********************************/
                                     if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) {
                                         // There should be no errors here
                                         define('AUTO_UPGRADE', true);
                                         require_once osc_lib_path() . 'osclass/upgrade-funcs.php';
                                     }
                                     // Additional actions is not important for the rest of the proccess
                                     // We will inform the user of the problems but the upgrade could continue
                                     /****************************
                                      ** REMOVE TEMPORARY FILES **
                                      ****************************/
                                     $path = ABS_PATH . 'oc-temp';
                                     $rm_errors = 0;
                                     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                                     for ($dir->rewind(); $dir->valid(); $dir->next()) {
                                         if ($dir->isDir()) {
                                             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                                 if (!rmdir($dir->getPathname())) {
                                                     $rm_errors++;
                                                 }
                                             }
                                         } else {
                                             if (!unlink($dir->getPathname())) {
                                                 $rm_errors++;
                                             }
                                         }
                                     }
                                     if (!rmdir($path)) {
                                         $rm_errors++;
                                     }
                                     $deleted = @unlink(ABS_PATH . '.maintenance');
                                     if ($rm_errors == 0) {
                                         $message = __('Everything was OK! Your OSClass installation is updated');
                                     } else {
                                         $message = __('Almost everything was OK! Your OSClass installation is updated, but there were some errors removing temporary files. Please, remove manually the "oc-temp" folder');
                                         $error = 6;
                                         // Some errors removing files
                                     }
                                 } else {
                                     $sql_error_msg = $error_queries[2];
                                     $message = __('Problems upgrading the database');
                                     $error = 5;
                                     // Problems upgrading the database
                                 }
                             } else {
                                 $message = __('Problems copying files. Maybe permissions are not correct');
                                 $error = 4;
                                 // Problems copying files. Maybe permissions are not correct
                             }
                         } else {
                             $message = __('Nothing to copy');
                             $error = 99;
                             // Nothing to copy. THIS SHOULD NEVER HAPPENS, means we dont update any file!
                         }
                     } else {
                         $message = __('Unzip failed');
                         $error = 3;
                         // Unzip failed
                     }
                 } else {
                     $message = __('Download failed');
                     $error = 2;
                     // Download failed
                 }
             } else {
                 $message = __('Missing download URL');
                 $error = 1;
                 // Missing download URL
             }
             if ($remove_error_msg != '') {
                 if ($error == 0) {
                     $message .= "<br /><br />" . __('We had some errors removing files, those are not super-sensitive errors, so we continued upgrading your installation. Please remove the following files (you already have OSClass upgraded, but to ensure maximun performance)');
                 }
             }
             if ($error == 5) {
                 $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed') . implode("<br />", $sql_error_msg);
             }
             echo $message;
             foreach ($perms as $k => $v) {
                 @chmod($k, $v);
             }
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Example #20
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->findByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->findByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             foreach ($cities as $k => $city) {
                 $cities[$k]['label'] = $city['label'] . " (" . $city['region'] . ")";
             }
             echo json_encode($cities);
             break;
         case 'location_countries':
             // This is the autocomplete AJAX
             $countries = Country::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($countries);
             break;
         case 'location_regions':
             // This is the autocomplete AJAX
             $regions = Region::newInstance()->ajax(Params::getParam("term"), Params::getParam("country"));
             echo json_encode($regions);
             break;
         case 'location_cities':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"), Params::getParam("region"));
             echo json_encode($cities);
             break;
         case 'delete_image':
             // Delete images via AJAX
             $ajax_photo = Params::getParam('ajax_photo');
             $id = Params::getParam('id');
             $item = Params::getParam('item');
             $code = Params::getParam('code');
             $secret = Params::getParam('secret');
             $json = array();
             if ($ajax_photo != '') {
                 $files = Session::newInstance()->_get('ajax_files');
                 $success = false;
                 foreach ($files as $uuid => $file) {
                     if ($file == $ajax_photo) {
                         $filename = $files[$uuid];
                         unset($files[$uuid]);
                         Session::newInstance()->_set('ajax_files', $files);
                         $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename);
                         break;
                     }
                 }
                 echo json_encode(array('success' => $success, 'msg' => $success ? _m('The selected photo has been successfully deleted') : _m("The selected photo couldn't be deleted")));
                 return false;
             }
             if (Session::newInstance()->_get('userId') != '') {
                 $userId = Session::newInstance()->_get('userId');
                 $user = User::newInstance()->findByPrimaryKey($userId);
             } else {
                 $userId = null;
                 $user = null;
             }
             // Check for required fields
             if (!(is_numeric($id) && is_numeric($item) && preg_match('/^([a-z0-9]+)$/i', $code))) {
                 $json['success'] = false;
                 $json['msg'] = _m("The selected photo couldn't be deleted, the url doesn't exist");
                 echo json_encode($json);
                 return false;
             }
             $aItem = Item::newInstance()->findByPrimaryKey($item);
             // Check if the item exists
             if (count($aItem) == 0) {
                 $json['success'] = false;
                 $json['msg'] = _m("The listing doesn't exist");
                 echo json_encode($json);
                 return false;
             }
             if (!osc_is_admin_user_logged_in()) {
                 // Check if the item belong to the user
                 if ($userId != null && $userId != $aItem['fk_i_user_id']) {
                     $json['success'] = false;
                     $json['msg'] = _m("The listing doesn't belong to you");
                     echo json_encode($json);
                     return false;
                 }
                 // Check if the secret passphrase match with the item
                 if ($userId == null && $aItem['fk_i_user_id'] == null && $secret != $aItem['s_secret']) {
                     $json['success'] = false;
                     $json['msg'] = _m("The listing doesn't belong to you");
                     echo json_encode($json);
                     return false;
                 }
             }
             // Does id & code combination exist?
             $result = ItemResource::newInstance()->existResource($id, $code);
             if ($result > 0) {
                 $resource = ItemResource::newInstance()->findByPrimaryKey($id);
                 if ($resource['fk_i_item_id'] == $item) {
                     // Delete: file, db table entry
                     if (defined(OC_ADMIN)) {
                         osc_deleteResource($id, true);
                         Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'admin', osc_logged_admin_id());
                     } else {
                         osc_deleteResource($id, false);
                         Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'user', osc_logged_user_id());
                     }
                     ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $item, 's_name' => $code));
                     $json['msg'] = _m('The selected photo has been successfully deleted');
                     $json['success'] = 'true';
                 } else {
                     $json['msg'] = _m("The selected photo does not belong to you");
                     $json['success'] = 'false';
                 }
             } else {
                 $json['msg'] = _m("The selected photo couldn't be deleted");
                 $json['success'] = 'false';
             }
             echo json_encode($json);
             return true;
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $encoded_alert = Params::getParam("alert");
             $alert = osc_decrypt_alert(base64_decode($encoded_alert));
             // check alert integrity / signature
             $stringToSign = osc_get_alert_public_key() . $encoded_alert;
             $signature = hex2b64(hmacsha1(osc_get_alert_private_key(), $stringToSign));
             $server_signature = Session::newInstance()->_get('alert_signature');
             if ($server_signature != $signature) {
                 echo '-2';
                 return false;
             }
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if (osc_is_web_user_logged_in()) {
                 $userid = osc_logged_user_id();
                 $user = User::newInstance()->findByPrimaryKey($userid);
                 $email = $user['s_email'];
             }
             if ($alert != '' && $email != '') {
                 if (osc_validate_email($email)) {
                     $secret = osc_genRandomPassword();
                     if ($alertID = Alerts::newInstance()->createAlert($userid, $email, $alert, $secret)) {
                         if ((int) $userid > 0) {
                             $user = User::newInstance()->findByPrimaryKey($userid);
                             if ($user['b_active'] == 1 && $user['b_enabled'] == 1) {
                                 Alerts::newInstance()->activate($alertID);
                                 echo '1';
                                 return true;
                             } else {
                                 echo '-1';
                                 return false;
                             }
                         } else {
                             $aAlert = Alerts::newInstance()->findByPrimaryKey($alertID);
                             osc_run_hook('hook_email_alert_validation', $aAlert, $email, $secret);
                         }
                         echo "1";
                     } else {
                         echo "0";
                     }
                     return true;
                 } else {
                     echo '-1';
                     return false;
                 }
             }
             echo '0';
             return false;
             break;
         case 'runhook':
             // run hooks
             $hook = Params::getParam('hook');
             if ($hook == '') {
                 echo json_encode(array('error' => 'hook parameter not defined'));
                 break;
             }
             switch ($hook) {
                 case 'item_form':
                     osc_run_hook('item_form', Params::getParam('catId'));
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     osc_run_hook('ajax_' . $hook);
                     break;
             }
             break;
         case 'custom':
             // Execute via AJAX custom file
             if (Params::existParam('route')) {
                 $routes = Rewrite::newInstance()->getRoutes();
                 $rid = Params::getParam('route');
                 $file = '../';
                 if (isset($routes[$rid]) && isset($routes[$rid]['file'])) {
                     $file = $routes[$rid]['file'];
                 }
             } else {
                 // DEPRECATED: Disclosed path in URL is deprecated, use routes instead
                 // This will be REMOVED in 3.4
                 $file = Params::getParam('ajaxfile');
             }
             if ($file == '') {
                 echo json_encode(array('error' => 'no action defined'));
                 break;
             }
             // valid file?
             if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || stripos($file, '/admin/') !== false) {
                 //If the file is inside an "admin" folder, it should NOT be opened in frontend
                 echo json_encode(array('error' => 'no valid ajaxFile'));
                 break;
             }
             if (!file_exists(osc_plugins_path() . $file)) {
                 echo json_encode(array('error' => "ajaxFile doesn't exist"));
                 break;
             }
             require_once osc_plugins_path() . $file;
             break;
         case 'check_username_availability':
             $username = osc_sanitize_username(Params::getParam('s_username'));
             if (!osc_is_username_blacklisted($username)) {
                 $user = User::newInstance()->findByUsername($username);
                 if (isset($user['s_username'])) {
                     echo json_encode(array('exists' => 1, 's_username' => $username));
                 } else {
                     echo json_encode(array('exists' => 0, 's_username' => $username));
                 }
             } else {
                 echo json_encode(array('exists' => 1, 's_username' => $username));
             }
             break;
         case 'ajax_upload':
             // Include the uploader class
             require_once LIB_PATH . "AjaxUploader.php";
             $uploader = new AjaxUploader();
             $original = pathinfo($uploader->getOriginalName());
             $filename = uniqid("qqfile_") . "." . $original['extension'];
             $result = $uploader->handleUpload(osc_content_path() . 'uploads/temp/' . $filename);
             $result['uploadName'] = $filename;
             echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
             break;
         case 'ajax_validate':
             $id = Params::getParam('id');
             if (!is_numeric($id)) {
                 echo json_encode(array('success' => false));
                 die;
             }
             $secret = Params::getParam('secret');
             $item = Item::newInstance()->findByPrimaryKey($id);
             if ($item['s_secret'] != $secret) {
                 echo json_encode(array('success' => false));
                 die;
             }
             $nResources = ItemResource::newInstance()->countResources($id);
             $result = array('success' => $nResources < osc_max_images_per_item(), 'count' => $nResources);
             echo json_encode($result);
             break;
         case 'delete_ajax_upload':
             $files = Session::newInstance()->_get('ajax_files');
             $success = false;
             $filename = '';
             if (isset($files[Params::getParam('qquuid')]) && $files[Params::getParam('qquuid')] != '') {
                 $filename = $files[Params::getParam('qquuid')];
                 unset($files[Params::getParam('qquuid')]);
                 Session::newInstance()->_set('ajax_files', $files);
                 $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename);
             }
             echo json_encode(array('success' => $success, 'uploadName' => $filename));
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Example #21
0
 function doModel()
 {
     switch ($this->action) {
         case 'dashboard':
             //dashboard...
             $max_items = Params::getParam('max_items') != '' ? Params::getParam('max_items') : 5;
             $aItems = Item::newInstance()->findByUserIDEnabled(Session::newInstance()->_get('userId'), 0, $max_items);
             //calling the view...
             $this->_exportVariableToView('items', $aItems);
             $this->_exportVariableToView('max_items', $max_items);
             $this->doView('user-dashboard.php');
             break;
         case 'profile':
             //profile...
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             $aCountries = Country::newInstance()->listAll();
             $aRegions = array();
             if ($user['fk_c_country_code'] != '') {
                 $aRegions = Region::newInstance()->findByCountry($user['fk_c_country_code']);
             } elseif (count($aCountries) > 0) {
                 $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
             }
             $aCities = array();
             if ($user['fk_i_region_id'] != '') {
                 $aCities = City::newInstance()->findByRegion($user['fk_i_region_id']);
             } else {
                 if (count($aRegions) > 0) {
                     $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
                 }
             }
             //calling the view...
             $this->_exportVariableToView('countries', $aCountries);
             $this->_exportVariableToView('regions', $aRegions);
             $this->_exportVariableToView('cities', $aCities);
             $this->_exportVariableToView('user', $user);
             $this->doView('user-profile.php');
             break;
         case 'profile_post':
             //profile post...
             $userId = Session::newInstance()->_get('userId');
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(false);
             $success = $userActions->edit($userId);
             osc_add_flash_ok_message(_m('Your profile has been updated successfully'));
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'alerts':
             //alerts
             $aAlerts = Alerts::newInstance()->findByUser(Session::newInstance()->_get('userId'));
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             foreach ($aAlerts as $k => $a) {
                 $search = osc_unserialize(base64_decode($a['s_search']));
                 $search->limit(0, 3);
                 $aAlerts[$k]['items'] = $search->doSearch();
             }
             $this->_exportVariableToView('alerts', $aAlerts);
             View::newInstance()->_reset('alerts');
             $this->_exportVariableToView('user', $user);
             $this->doView('user-alerts.php');
             break;
         case 'change_email':
             //change email
             $this->doView('user-change_email.php');
             break;
         case 'change_email_post':
             //change email post
             if (!preg_match("/^[_a-z0-9-\\+]+(\\.[_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})\$/", Params::getParam('new_email'))) {
                 osc_add_flash_error_message(_m('The specified e-mail is not valid'));
                 $this->redirectTo(osc_change_user_email_url());
             } else {
                 $user = User::newInstance()->findByEmail(Params::getParam('new_email'));
                 if (!isset($user['pk_i_id'])) {
                     $userEmailTmp = array();
                     $userEmailTmp['fk_i_user_id'] = Session::newInstance()->_get('userId');
                     $userEmailTmp['s_new_email'] = Params::getParam('new_email');
                     UserEmailTmp::newInstance()->insertOrUpdate($userEmailTmp);
                     $code = osc_genRandomPassword(30);
                     $date = date('Y-m-d H:i:s');
                     $userManager = new User();
                     $userManager->update(array('s_pass_code' => $code, 's_pass_date' => $date, 's_pass_ip' => $_SERVER['REMOTE_ADDR']), array('pk_i_id' => Session::newInstance()->_get('userId')));
                     $validation_url = osc_change_user_email_confirm_url(Session::newInstance()->_get('userId'), $code);
                     osc_run_hook('hook_email_new_email', Params::getParam('new_email'), $validation_url);
                     $this->redirectTo(osc_user_profile_url());
                 } else {
                     osc_add_flash_error_message(_m('The specified e-mail is already in use'));
                     $this->redirectTo(osc_change_user_email_url());
                 }
             }
             break;
         case 'change_password':
             //change password
             $this->doView('user-change_password.php');
             break;
         case 'change_password_post':
             //change password post
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             if (Params::getParam('password') == '' || Params::getParam('new_password') == '' || Params::getParam('new_password2') == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if ($user['s_password'] != sha1(Params::getParam('password'))) {
                 osc_add_flash_error_message(_m('Current password doesn\'t match'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (!Params::getParam('new_password')) {
                 osc_add_flash_error_message(_m('Passwords can\'t be empty'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (Params::getParam('new_password') != Params::getParam('new_password2')) {
                 osc_add_flash_error_message(_m('Passwords don\'t match'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             User::newInstance()->update(array('s_password' => sha1(Params::getParam('new_password'))), array('pk_i_id' => Session::newInstance()->_get('userId')));
             osc_add_flash_ok_message(_m('Password has been changed'));
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'items':
             // view items user
             $itemsPerPage = Params::getParam('itemsPerPage') != '' ? Params::getParam('itemsPerPage') : 5;
             $page = Params::getParam('iPage') != '' ? Params::getParam('iPage') : 0;
             $total_items = Item::newInstance()->countByUserIDEnabled($_SESSION['userId']);
             $total_pages = ceil($total_items / $itemsPerPage);
             $items = Item::newInstance()->findByUserIDEnabled($_SESSION['userId'], $page * $itemsPerPage, $itemsPerPage);
             $this->_exportVariableToView('items', $items);
             $this->_exportVariableToView('list_total_pages', $total_pages);
             $this->_exportVariableToView('list_total_items', $total_items);
             $this->_exportVariableToView('items_per_page', $itemsPerPage);
             $this->_exportVariableToView('list_page', $page);
             $this->doView('user-items.php');
             break;
         case 'activate_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $result = 0;
             if ($email != '' && $secret != '') {
                 $result = Alerts::newInstance()->activate($email, $secret);
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Alert activated'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to activate alert. Please contact the administrator'));
             }
             $this->redirectTo(osc_base_url(true));
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             if ($email != '' && $secret != '') {
                 Alerts::newInstance()->delete(array('s_email' => $email, 's_secret' => $secret));
                 osc_add_flash_ok_message(_m('Unsubscribed correctly'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to unsubscribe you. Please contact the administrator'));
             }
             $this->redirectTo(osc_user_alerts_url());
             break;
         case 'deleteResource':
             $id = Params::getParam('id');
             $name = Params::getParam('name');
             $fkid = Params::getParam('fkid');
             osc_deleteResource($id);
             ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $fkid, 's_name' => $name));
             $this->redirectTo(osc_base_url(true) . "?page=item&action=item_edit&id=" . $fkid);
             break;
     }
 }
Example #22
0
// 		both 										<-- delete files and truncate database
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
// HTTP 1.1.
header("Pragma: no-cache");
// HTTP 1.0.
header("Expires: 0");
// Proxies.
require_once '../config.php';
function __autoload($class_name)
{
    include "../" . APP_CLASSES . "{$class_name}.class.php";
}
$html = new Frontend();
$report = new Report();
$alerts = new Alerts();
$scripts = new Scripts();
$_SESSION['display'] = isset($_GET['display']) ? $_GET['display'] : true;
if ($_SESSION['display']) {
    echo '<div class="container-fluid"><div class="row"><div class="col-xs-12 text-center"><h3>Running Cleanse</h3></div></div><div class="row"><hr /><div class="col-xs-10 col-xs-offset-1">';
}
///////////////////
// Start Script	 //
///////////////////
if (isset($_GET['clean'])) {
    switch ($_GET['clean']) {
        case 'logs':
            $scripts->clean_log_tables();
            break;
        case 'reindex':
            $scripts->fix_reindex_error();
Example #23
0
// 		true 										<-- displays deletion on screen
// 		scan 										<-- only show contents of directories to screen
// 		both 										<-- delete files and truncate database
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
// HTTP 1.1.
header("Pragma: no-cache");
// HTTP 1.0.
header("Expires: 0");
// Proxies.
require_once '../config.php';
function __autoload($class_name)
{
    include "../" . APP_CLASSES . "{$class_name}.class.php";
}
$html = new Frontend();
$report = new Report();
$alerts = new Alerts();
$scripts = new Scripts();
$db = new Database();
$barcodes = $db->select("barcodes");
foreach ($barcodes as $barcode) {
    $bc = $barcode['barcode'];
    if ($bc[0] == 2) {
        $db->delete("barcodes", $barcode['id']);
    }
}
$html->footer(false);
if ($alerts->trigger !== false) {
    $alerts->trigger();
}
Example #24
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->getByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->getByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $alert = Params::getParam("alert");
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if ($alert != '' && $email != '') {
                 Alerts::newInstance()->insert(array('fk_i_user_id' => $userid, 's_email' => $email, 's_search' => $alert, 'e_type' => 'DAILY'));
                 echo "1";
                 return true;
             }
             echo '0';
             return false;
             break;
         case 'runhook':
             //Run hooks
             $hook = Params::getParam("hook");
             switch ($hook) {
                 case 'item_form':
                     $catId = Params::getParam("catId");
                     if ($catId != '') {
                         osc_run_hook("item_form", $catId);
                     } else {
                         osc_run_hook("item_form");
                     }
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     if ($hook == '') {
                         return false;
                     } else {
                         osc_run_hook($hook);
                     }
                     break;
             }
             break;
         case 'items':
             // Return items (use external file oc-admin/ajax/item_processing.php)
             require_once osc_admin_base_path() . 'ajax/items_processing.php';
             $items_processing = new items_processing_ajax(Params::getParamsAsArray("get"));
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxfile = Params::getParam("ajaxfile");
             if ($ajaxfile != '') {
                 require_once osc_admin_base_path() . $ajaxfile;
             } else {
                 echo json_encode(array('error' => __('no action defined')));
             }
             break;
             /******************************
              ** COMPLETE UPGRADE PROCESS **
              ******************************/
         /******************************
          ** COMPLETE UPGRADE PROCESS **
          ******************************/
         case 'upgrade':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             $message = "";
             $error = 0;
             $remove_error_msg = "";
             $sql_error_msg = "";
             $rm_errors = 0;
             $perms = osc_save_permissions();
             osc_change_permissions();
             /***********************
              **** DOWNLOAD FILE ****
              ***********************/
             if (Params::getParam('file') != '') {
                 $tmp = explode("/", Params::getParam('file'));
                 $filename = end($tmp);
                 $result = osc_downloadFile(Params::getParam('file'), $filename);
                 if ($result) {
                     // Everything is OK, continue
                     /**********************
                      ***** UNZIP FILE *****
                      **********************/
                     @mkdir(ABS_PATH . 'oc-temp', 0777);
                     $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/');
                     if ($res == 1) {
                         // Everything is OK, continue
                         /**********************
                          ***** COPY FILES *****
                          **********************/
                         $fail = -1;
                         if ($handle = opendir(ABS_PATH . 'oc-temp')) {
                             $fail = 0;
                             while (false !== ($_file = readdir($handle))) {
                                 if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') {
                                     $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file);
                                     if ($data == false) {
                                         $fail = 1;
                                     }
                                 }
                             }
                             closedir($handle);
                             if ($fail == 0) {
                                 // Everything is OK, continue
                                 /**********************
                                  **** REMOVE FILES ****
                                  **********************/
                                 if (file_exists(ABS_PATH . 'oc-temp/remove.list')) {
                                     $lines = file(ABS_PATH . 'oc-temp/remove.list', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                                     foreach ($lines as $line_num => $r_file) {
                                         $unlink = @unlink(ABS_PATH . $r_file);
                                         if (!$unlink) {
                                             $remove_error_msg .= __('Error removing file: ') . $r_file . "<br/>";
                                         }
                                     }
                                 }
                                 // Removing files is not important for the rest of the proccess
                                 // We will inform the user of the problems but the upgrade could continue
                                 /************************
                                  *** UPGRADE DATABASE ***
                                  ************************/
                                 $error_queries = array();
                                 if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) {
                                     $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql');
                                     $conn = getConnection();
                                     $error_queries = $conn->osc_updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql));
                                 }
                                 if ($error_queries[0]) {
                                     // Everything is OK, continue
                                     /**********************************
                                      ** EXECUTING ADDITIONAL ACTIONS **
                                      **********************************/
                                     if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) {
                                         // There should be no errors here
                                         require_once osc_lib_path() . 'osclass/upgrade-funcs.php';
                                     }
                                     // Additional actions is not important for the rest of the proccess
                                     // We will inform the user of the problems but the upgrade could continue
                                     /****************************
                                      ** REMOVE TEMPORARY FILES **
                                      ****************************/
                                     $path = ABS_PATH . 'oc-temp';
                                     $rm_errors = 0;
                                     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                                     for ($dir->rewind(); $dir->valid(); $dir->next()) {
                                         if ($dir->isDir()) {
                                             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                                 if (!rmdir($dir->getPathname())) {
                                                     $rm_errors++;
                                                 }
                                             }
                                         } else {
                                             if (!unlink($dir->getPathname())) {
                                                 $rm_errors++;
                                             }
                                         }
                                     }
                                     if (!rmdir($path)) {
                                         $rm_errors++;
                                     }
                                     if ($rm_errors == 0) {
                                         $message = __('Everything was OK! Your OSClass installation is updated');
                                     } else {
                                         $message = __('Almost everything was OK! Your OSClass installation is updated, but there were some errors removing temporary files. Please, remove manually the "oc-temp" folder', 'admin');
                                         $error = 6;
                                         // Some errors removing files
                                     }
                                 } else {
                                     $sql_error_msg = $error_queries[2];
                                     $message = __('Problems upgrading the database', 'admin');
                                     $error = 5;
                                     // Problems upgrading the database
                                 }
                             } else {
                                 $message = __('Problems copying files. Maybe permissions are not correct', 'admin');
                                 $error = 4;
                                 // Problems copying files. Maybe permissions are not correct
                             }
                         } else {
                             $message = __('Nothing to copy', 'admin');
                             $error = 99;
                             // Nothing to copy. THIS SHOULD NEVER HAPPENS, means we dont update any file!
                         }
                     } else {
                         $message = __('Unzip failed', 'admin');
                         $error = 3;
                         // Unzip failed
                     }
                 } else {
                     $message = __('Download failed', 'admin');
                     $error = 2;
                     // Download failed
                 }
             } else {
                 $message = __('Missing download URL', 'admin');
                 $error = 1;
                 // Missing download URL
             }
             if ($remove_error_msg != '') {
                 if ($error == 0) {
                     $message .= "<br /><br />" . __('We had some errors removing files, those are not super-sensitive errors, so we continued upgrading your installation. Please remove the following files (you already have OSClass upgraded, but to ensure maximun performance)', 'admin');
                 }
             }
             if ($error == 5) {
                 $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed', 'admin') . implode("<br />", $sql_error_msg);
             }
             echo $message;
             foreach ($perms as $k => $v) {
                 chmod($k, $v);
             }
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
 }
Example #25
0
 function doModel()
 {
     switch ($this->action) {
         case 'dashboard':
             //dashboard...
             $max_items = Params::getParam('max_items') != '' ? Params::getParam('max_items') : 5;
             $aItems = Item::newInstance()->findByUserID(Session::newInstance()->_get('userId'), 0, $max_items);
             //Item::newInstance()->listWhere("fk_i_user_id = ".Session::newInstance()->_get('userId'));
             //calling the view...
             $this->_exportVariableToView('items', $aItems);
             $this->_exportVariableToView('max_items', $max_items);
             $this->doView('user-dashboard.php');
             break;
         case 'profile':
             //profile...
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             $aCountries = Country::newInstance()->listAll();
             $aRegions = array();
             if ($user['fk_c_country_code'] != '') {
                 $aRegions = Region::newInstance()->getByCountry($user['fk_c_country_code']);
             } elseif (count($aCountries) > 0) {
                 $aRegions = Region::newInstance()->getByCountry($aCountries[0]['pk_c_code']);
             }
             $aCities = array();
             if ($user['fk_i_region_id'] != '') {
                 $aCities = City::newInstance()->listWhere("fk_i_region_id = %d", $user['fk_i_region_id']);
             } else {
                 if (count($aRegions) > 0) {
                     $aCities = City::newInstance()->listWhere("fk_i_region_id = %d", $aRegions[0]['pk_i_id']);
                 }
             }
             //calling the view...
             $this->_exportVariableToView('countries', $aCountries);
             $this->_exportVariableToView('regions', $aRegions);
             $this->_exportVariableToView('cities', $aCities);
             $this->_exportVariableToView('user', $user);
             $this->doView('user-profile.php');
             break;
         case 'profile_post':
             //profile post...
             $userId = Session::newInstance()->_get('userId');
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(false);
             $success = $userActions->edit($userId);
             // This has been moved to special area (only password changes)
             /*if( $success == 1 ) {
                   osc_add_flash_message( _m('Passwords don\'t match') ) ;
               } else {*/
             osc_add_flash_message(_m('Your profile has been updated successfully'));
             //}
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'alerts':
             //alerts
             $aAlerts = Alerts::newInstance()->getAlertsFromUser(Session::newInstance()->_get('userId'));
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             foreach ($aAlerts as $k => $a) {
                 $search = osc_unserialize(base64_decode($a['s_search']));
                 $search->limit(0, 3);
                 $aAlerts[$k]['items'] = $search->doSearch();
             }
             $this->_exportVariableToView('alerts', $aAlerts);
             View::newInstance()->_reset('alerts');
             $this->_exportVariableToView('user', $user);
             $this->doView('user-alerts.php');
             break;
         case 'change_email':
             //change email
             $this->doView('user-change_email.php');
             break;
         case 'change_email_post':
             //change email post
             if (!preg_match("/^[_a-z0-9-\\+]+(\\.[_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})\$/", Params::getParam('new_email'))) {
                 osc_add_flash_message(_m('The specified e-mail is not valid'));
                 $this->redirectTo(osc_change_user_email_url());
             } else {
                 $user = User::newInstance()->findByEmail(Params::getParam('new_email'));
                 if (!isset($user['pk_i_id'])) {
                     if (osc_user_validation_enabled()) {
                         $userEmailTmp = array();
                         $userEmailTmp['fk_i_user_id'] = Session::newInstance()->_get('userId');
                         $userEmailTmp['s_new_email'] = Params::getParam('new_email');
                         UserEmailTmp::newInstance()->insertOrUpdate($userEmailTmp);
                         $code = osc_genRandomPassword(30);
                         $date = date('Y-m-d H:i:s');
                         $userManager = new User();
                         $userManager->update(array('s_pass_code' => $code, 's_pass_date' => $date, 's_pass_ip' => $_SERVER['REMOTE_ADDR']), array('pk_i_id' => Session::newInstance()->_get('userId')));
                         $locale = osc_current_user_locale();
                         $aPage = Page::newInstance()->findByInternalName('email_new_email');
                         if (isset($aPage['locale'][$locale]['s_title'])) {
                             $content = $aPage['locale'][$locale];
                         } else {
                             $content = current($aPage['locale']);
                         }
                         if (!is_null($content)) {
                             $validation_url = osc_change_user_email_confirm_url(Session::newInstance()->_get('userId'), $code);
                             $words = array();
                             $words[] = array('{USER_NAME}', '{USER_EMAIL}', '{WEB_URL}', '{WEB_TITLE}', '{VALIDATION_LINK}', '{VALIDATION_URL}');
                             $words[] = array(Session::newInstance()->_get('userName'), Params::getParam('new_email'), osc_base_url(), osc_page_title(), '<a href="' . $validation_url . '" >' . $validation_url . '</a>', $validation_url);
                             $title = osc_mailBeauty($content['s_title'], $words);
                             $body = osc_mailBeauty($content['s_text'], $words);
                             $params = array('subject' => $title, 'to' => Params::getParam('new_email'), 'to_name' => Session::newInstance()->_get('userName'), 'body' => $body, 'alt_body' => $body);
                             osc_sendMail($params);
                             osc_add_flash_message(_m('We have sent you an e-mail. Follow the instructions to validate the changes'));
                         } else {
                             osc_add_flash_message(_m('We tried to sent you an e-mail, but it failed. Please, contact the administrator'));
                         }
                         $this->redirectTo(osc_user_profile_url());
                     } else {
                         User::newInstance()->update(array('s_email' => Params::getParam('new_email')), array('pk_i_id' => Params::getParam('userId')));
                         osc_add_flash_message(_m('Your email has been changed successfully'));
                         $this->redirectTo(osc_user_profile_url());
                     }
                 } else {
                     osc_add_flash_message(_m('The specified e-mail is already in use'));
                     $this->redirectTo(osc_change_user_email_url());
                 }
             }
             break;
         case 'change_password':
             //change password
             $this->doView('user-change_password.php');
             break;
         case 'change_password_post':
             //change password post
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             if ($user['s_password'] != sha1(Params::getParam('password'))) {
                 osc_add_flash_message(_m('Current password doesn\'t match'));
                 $this->redirectTo(osc_change_user_password_url());
             } elseif (!Params::getParam('new_password')) {
                 osc_add_flash_message(_m('Passwords can\'t be empty'));
                 $this->redirectTo(osc_change_user_password_url());
             } elseif (Params::getParam('new_password') != Params::getParam('new_password2')) {
                 osc_add_flash_message(_m('Passwords don\'t match'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             User::newInstance()->update(array('s_password' => sha1(Params::getParam('new_password'))), array('pk_i_id' => Session::newInstance()->_get('userId')));
             osc_add_flash_message(_m('Password has been changed'));
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'items':
             // view items user
             $itemsPerPage = Params::getParam('itemsPerPage') != '' ? Params::getParam('itemsPerPage') : 5;
             $page = Params::getParam('iPage') != '' ? Params::getParam('iPage') : 0;
             $total_items = Item::newInstance()->countByUserID($_SESSION['userId']);
             $total_pages = ceil($total_items / $itemsPerPage);
             $items = Item::newInstance()->findByUserID($_SESSION['userId'], $page * $itemsPerPage, $itemsPerPage);
             $this->_exportVariableToView('items', $items);
             $this->_exportVariableToView('list_total_pages', $total_pages);
             $this->_exportVariableToView('list_total_items', $total_items);
             $this->_exportVariableToView('items_per_page', $itemsPerPage);
             $this->_exportVariableToView('list_page', $page);
             $this->doView('user-items.php');
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $alert = Params::getParam('alert');
             if ($email != '' && $alert != '') {
                 Alerts::newInstance()->delete(array('s_email' => $email, 's_search' => $alert));
                 osc_add_flash_message(__('Unsubscribed correctly.'));
             } else {
                 osc_add_flash_message(__('Ops! There was a problem trying to unsubscribe you. Please contact the administrator.'));
             }
             $this->redirectTo(osc_user_alerts_url());
             break;
     }
 }
 public function dashboard()
 {
     $user_id = Session::get('user_id');
     $practice_id = Session::get('practice_id');
     $data['practiceinfo'] = Practiceinfo::find($practice_id);
     $result = User::find($user_id);
     $data['displayname'] = $result->displayname;
     $displayname = $result->displayname;
     $fax_query = Received::where('practice_id', '=', $practice_id)->count();
     $from = $displayname . ' (' . $user_id . ')';
     if (Session::get('group_id') == '2') {
         $data['number_messages'] = Messaging::where('mailbox', '=', $user_id)->count();
         $data['number_documents'] = Scans::where('practice_id', '=', $practice_id)->count() + $fax_query;
         $data['number_appts'] = $this->getNumberAppts($user_id);
         $query1 = DB::table('t_messages')->join('demographics', 't_messages.pid', '=', 'demographics.pid')->where('t_messages.t_messages_from', '=', $from)->where('t_messages.t_messages_signed', '=', 'No')->count();
         $query2 = DB::table('encounters')->join('demographics', 'encounters.pid', '=', 'demographics.pid')->where('encounters.encounter_provider', '=', $displayname)->where('encounters.encounter_signed', '=', 'No')->count();
         $data['number_drafts'] = $query1 + $query2;
         $data['number_reminders'] = DB::table('alerts')->join('demographics', 'alerts.pid', '=', 'demographics.pid')->where('alerts.alert_provider', '=', $user_id)->where('alerts.alert_date_complete', '=', '0000-00-00 00:00:00')->where('alerts.alert_reason_not_complete', '=', '')->where(function ($query_array) {
             $query_array->where('alerts.alert', '=', 'Laboratory results pending')->orWhere('alerts.alert', '=', 'Radiology results pending')->orWhere('alerts.alert', '=', 'Cardiopulmonary results pending')->orWhere('alerts.alert', '=', 'Referral pending')->orWhere('alerts.alert', '=', 'Reminder')->orWhere('alerts.alert', '=', 'REMINDER');
         })->count();
         $data['number_bills'] = Encounters::where('bill_submitted', '=', 'No')->where('user_id', '=', $user_id)->count();
         $data['number_tests'] = Tests::whereNull('pid')->where('practice_id', '=', $practice_id)->count();
         if ($data['practiceinfo']->mtm_extension == 'y') {
             $mtm_users_array = explode(",", $data['practiceinfo']->mtm_alert_users);
             if (in_array($user_id, $mtm_users_array)) {
                 $data['mtm_alerts'] = Alerts::where('alert_date_complete', '=', '0000-00-00 00:00:00')->where('alert_reason_not_complete', '=', '')->where('alert', '=', 'Medication Therapy Management')->where('practice_id', '=', $practice_id)->count();
                 $data['mtm_alerts_status'] = "y";
             } else {
                 $data['mtm_alerts_status'] = "n";
             }
         } else {
             $data['mtm_alerts_status'] = "n";
         }
         $data['vaccine_supplement_alert'] = $this->vaccine_supplement_alert($practice_id);
     }
     if (Session::get('group_id') == '3') {
         $data['number_messages'] = Messaging::where('mailbox', '=', $user_id)->count();
         $data['number_documents'] = Scans::where('practice_id', '=', $practice_id)->count() + $fax_query;
         $data['number_drafts'] = DB::table('t_messages')->join('demographics', 't_messages.pid', '=', 'demographics.pid')->where('t_messages.t_messages_from', '=', $from)->where('t_messages.t_messages_signed', '=', 'No')->count();
         $data['number_reminders'] = DB::table('alerts')->join('demographics', 'alerts.pid', '=', 'demographics.pid')->where('alerts.alert_provider', '=', $user_id)->where('alerts.alert_date_complete', '=', '0000-00-00 00:00:00')->where('alerts.alert_reason_not_complete', '=', '')->where(function ($query_array) {
             $query_array->where('alerts.alert', '=', 'Laboratory results pending')->orWhere('alerts.alert', '=', 'Radiology results pending')->orWhere('alerts.alert', '=', 'Cardiopulmonary results pending')->orWhere('alerts.alert', '=', 'Referral pending')->orWhere('alerts.alert', '=', 'Reminder')->orWhere('alerts.alert', '=', 'REMINDER');
         })->count();
         $data['number_bills'] = Encounters::where('bill_submitted', '=', 'No')->where('practice_id', '=', $practice_id)->count();
         $data['number_tests'] = Tests::whereNull('pid')->where('practice_id', '=', $practice_id)->count();
         $data['vaccine_supplement_alert'] = $this->vaccine_supplement_alert($practice_id);
     }
     if (Session::get('group_id') == '4') {
         $data['number_messages'] = Messaging::where('mailbox', '=', $user_id)->count();
         $data['number_bills'] = Encounters::where('bill_submitted', '=', 'No')->where('practice_id', '=', $practice_id)->count();
         $data['number_documents'] = Scans::where('practice_id', '=', $practice_id)->count() + $fax_query;
     }
     if (Session::get('group_id') == '100') {
         $row = Demographics_relate::where('id', '=', $user_id)->first();
         Session::put('pid', $row->pid);
     }
     if (Session::get('group_id') == '1') {
         if ($practice_id == '1') {
             $data['saas_admin'] = 'y';
         } else {
             $data['saas_admin'] = 'n';
         }
         if (Session::get('patient_centric') != 'y') {
             $users = DB::table('users')->where('group_id', '=', '2')->where('practice_id', '=', Session::get('practice_id'))->first();
             if ($users) {
                 $data['users_needed'] = 'n';
             } else {
                 $data['users_needed'] = 'y';
             }
         } else {
             $data['users_needed'] = 'n';
         }
         if (Session::get('patient_centric') != 'y') {
             $schedule = DB::table('practiceinfo')->where('practice_id', '=', Session::get('practice_id'))->whereNull('minTime')->first();
             if ($schedule) {
                 $data['schedule_needed'] = 'y';
             } else {
                 $data['schedule_needed'] = 'n';
             }
         } else {
             $data['schedule_needed'] = 'n';
         }
     }
     if ($data['practiceinfo']->weekends == '1') {
         $data['weekends'] = 'true';
     } else {
         $data['weekends'] = 'false';
     }
     $data['minTime'] = ltrim($data['practiceinfo']->minTime, "0");
     $data['maxTime'] = ltrim($data['practiceinfo']->maxTime, "0");
     if (Session::get('group_id') == '2') {
         $provider = Providers::find(Session::get('user_id'));
         $data['schedule_increment'] = $provider->schedule_increment;
     } else {
         $data['schedule_increment'] = '15';
     }
     if (!Session::get('encounter_active')) {
         Session::put('encounter_active', 'n');
     }
     if ($data['practiceinfo']->fax_type != "") {
         $data1['fax'] = true;
     } else {
         $data1['fax'] = false;
     }
     $this->layout->style = $this->css_assets();
     $this->layout->script = $this->js_assets('home');
     $this->layout->content = '';
     if (Session::get('group_id') == '1') {
         $this->layout->content .= View::make('search', $this->getSearchData())->render();
         $this->layout->content .= View::make('dashboard', $data)->render();
         $this->layout->content .= View::make('setup')->render();
         $this->layout->content .= View::make('users')->render();
         $this->layout->content .= View::make('extensions', $data)->render();
         $this->layout->content .= View::make('schedule_admin')->render();
         $this->layout->content .= View::make('update')->render();
         $this->layout->content .= View::make('logs')->render();
         $this->layout->content .= View::make('schedule')->render();
     }
     if (Session::get('group_id') == '2' || Session::get('group_id') == '3' || Session::get('group_id') == '4') {
         $this->layout->content .= View::make('search', $this->getSearchData())->render();
         $this->layout->content .= View::make('dashboard', $data)->render();
         $this->layout->content .= View::make('demographics')->render();
         $this->layout->content .= View::make('options')->render();
         $this->layout->content .= View::make('messaging', $data1)->render();
         $this->layout->content .= View::make('schedule')->render();
         $this->layout->content .= View::make('billing')->render();
         $this->layout->content .= View::make('financial')->render();
         $this->layout->content .= View::make('office')->render();
         if (Session::get('patient_centric') == 'yp' && Session::get('group_id') == '2') {
             $this->layout->content .= View::make('setup')->render();
         }
     }
     if (Session::get('group_id') == '100') {
         $this->layout->content .= View::make('dashboard', $data)->render();
         $this->layout->content .= View::make('demographics')->render();
         $this->layout->content .= View::make('messaging', $data1)->render();
         $this->layout->content .= View::make('schedule')->render();
         $this->layout->content .= View::make('issues')->render();
         $this->layout->content .= View::make('encounters')->render();
         $this->layout->content .= View::make('t_messages')->render();
         $this->layout->content .= View::make('medications')->render();
         $this->layout->content .= View::make('supplements')->render();
         $this->layout->content .= View::make('allergies')->render();
         $this->layout->content .= View::make('immunizations')->render();
         $this->layout->content .= View::make('documents')->render();
         $this->layout->content .= View::make('forms')->render();
         $this->layout->content .= View::make('graph')->render();
     }
 }
Example #27
0
 /**
  * @param $model_class
  * @param $array
  *
  * @return bool|\yii\db\ActiveRecord
  * @throws \yii\base\InvalidConfigException
  * @throws \yii\db\Exception
  */
 public static function saveModelForm($model_class, $array)
 {
     /** @var  $model \yii\db\ActiveRecord */
     $model = new $model_class();
     if (isset($array['id']) && $array['id']) {
         $model->setIsNewRecord(FALSE);
     }
     foreach ($array as $k => $v) {
         $model[$k] = $v;
     }
     if ($model->isNewRecord && $model->validate() && $model->save()) {
         return $model;
     }
     if (!$model->isNewRecord) {
         $sql = "UPDATE " . $model->getTableSchema()->fullName . " ";
         $sql .= "SET ";
         foreach ($array as $k => $v) {
             if ($k == "id") {
                 continue;
             }
             $sql .= "`" . strtolower(trim($k)) . "` = '" . addslashes(trim($v)) . "',";
         }
         $sql = rtrim($sql, ',');
         $sql .= " WHERE `id` = " . $array['id'];
         Yii::$app->db->createCommand($sql)->execute();
         return $model;
     }
     echo PHP_EOL . $model_class . "<BR>" . PHP_EOL;
     print_r($model->getErrors());
     exit;
     Alerts::setMessage('Model: ' . $model_class . '<br>Error: ' . print_r($model->getErrors(), TRUE));
     Alerts::setAlertType(Alerts::ALERT_DANGER);
     return FALSE;
 }
Example #28
0
        $this->warningMessage = $message;
        $this->warning = true;
    }
    public function setSuccess($message)
    {
        $this->successMessage = $message;
        $this->success = true;
    }
    public function unsetError()
    {
        $this->error = false;
    }
    public function unsetWarning()
    {
        $this->warning = false;
    }
    public function unsetSuccess()
    {
        $this->success = false;
    }
}
$alerts = new Alerts();
if (isset($_GET['error'])) {
    $alerts->setError($_GET['error']);
}
if (isset($_GET['warning'])) {
    $alerts->setWarning($_GET['warning']);
}
if (isset($_GET['success'])) {
    $alerts->setSuccess($_GET['success']);
}
 public function postAlertsList($mobile = false)
 {
     $query = Alerts::where('pid', '=', Session::get('pid'))->where('alert_date_active', '<=', date('Y-m-d H:i:s', time() + 1209600))->where('alert_date_complete', '=', '0000-00-00 00:00:00')->where('alert_reason_not_complete', '=', '')->where('practice_id', '=', Session::get('practice_id'))->get();
     $result = '';
     if ($query) {
         if ($mobile == false) {
             $result .= '<ul>';
             foreach ($query as $row) {
                 $result .= '<li>' . $row->alert . ' (Due ' . date('m/d/Y', $this->human_to_unix($row->alert_date_active)) . ') - ' . $row->alert_description . '</li>';
             }
             $result .= '</ul>';
         } else {
             $list_array = [];
             $form = [];
             $i = 1;
             $columns = Schema::getColumnListing('alerts');
             $row_index = $columns[0];
             $list_array[] = ['label' => 'Add Alert', 'pid' => Session::get('pid'), 'href' => action('AjaxChartController@postMobileEditPage', array('alerts', $row_index, '0')), 'origin' => '../ajaxchart/alerts-list/true'];
             foreach ($query as $row) {
                 $list_array[] = ['label' => $row->alert . ' (Due ' . date('m/d/Y', $this->human_to_unix($row->alert_date_active)) . ') - ' . $row->alert_description, 'pid' => Session::get('pid'), 'href' => action('AjaxChartController@postMobileEditPage', array('alerts', $row_index, $row->{$row_index})), 'origin' => '../ajaxchart/alerts-list/true'];
             }
             $result .= $this->mobile_result_build($list_array, 'mobile_allergies_list');
         }
     } else {
         $result .= ' None.';
     }
     echo $result;
 }
Example #30
0
function osc_runAlert($type = null)
{
    if ($type == null) {
        return;
    }
    $internal_name = 'alert_email_hourly';
    switch ($type) {
        case 'HOURLY':
            $internal_name = 'alert_email_hourly';
            break;
        case 'DAILY':
            $internal_name = 'alert_email_daily';
            break;
        case 'WEEKLY':
            $internal_name = 'alert_email_weekly';
            break;
        case 'INSTANT':
            $internal_name = 'alert_email_instant';
            break;
    }
    $searches = Alerts::newInstance()->getAlertsByTypeGroup($type);
    foreach ($searches as $s_search) {
        $a_search = Search::newInstance();
        // Get if there're new ads on this search
        $a_search = osc_unserialize(base64_decode($s_search['s_search']));
        $crons = Cron::newInstance()->getCronByType($type);
        if (isset($crons[0])) {
            $last_exec = $crons[0]['d_last_exec'];
        } else {
            $last_exec = '0000-00-00 00:00:00';
        }
        $a_search->addConditions(sprintf(" %st_item.dt_pub_date > '%s' ", DB_TABLE_PREFIX, $last_exec));
        $totalItems = $a_search->count();
        $items = $a_search->doSearch();
        if (count($items) > 0) {
            //If we have new items from last check
            //Catch the user subscribed to this search
            $users = Alerts::newInstance()->getUsersBySearchAndType($s_search['s_search'], $type);
            if (count($users) > 0) {
                $prefLocale = osc_language();
                $page = Page::newInstance()->findByInternalName($internal_name);
                $page = Page::newInstance()->findByInternalName($internal_name);
                $page_description = $page['locale'];
                $_title = $page_description[$prefLocale]['s_title'];
                $_body = $page_description[$prefLocale]['s_text'];
                $ads = "";
                foreach ($items as $item) {
                    $ads .= '<a href="' . osc_item_url_ns($item['pk_i_id']) . '">' . $item['s_title'] . '</a><br/>';
                }
                foreach ($users as $user) {
                    if ($user['fk_i_user_id'] != 0) {
                        $user = User::newInstance()->findByPrimaryKey($user['fk_i_user_id']);
                    } else {
                        $user['s_name'] = $user['s_email'];
                    }
                    $unsub_link = osc_user_unsubscribe_alert_url($user['s_email'], $s_search['s_search']);
                    //osc_create_url(array('file' => 'user', 'action' => 'unsub_alert', 'email' => $user['s_email'], 'alert' => $s_search['s_search'])) ;
                    $unsub_link = '<a href="' . $unsub_link . '">unsubscribe alert</a>';
                    $words = array();
                    $words[] = array('{USER_NAME}', '{USER_EMAIL}', '{ADS}', '{UNSUB_LINK}');
                    $words[] = array($user['s_name'], $user['s_email'], $ads, $unsub_link);
                    $title = osc_mailBeauty($_title, $words);
                    $body = osc_mailBeauty($_body, $words);
                    $params = array('subject' => $title, 'to' => $user['s_email'], 'to_name' => $user['s_name'], 'body' => $body, 'alt_body' => $body);
                    osc_sendMail($params);
                }
            }
        }
    }
}