function osc_has_static_pages_seo() { if (!View::newInstance()->_exists('pages')) { View::newInstance()->_exportVariableToView('pages', Page::newInstance()->listAll(false, 0)); } $page = View::newInstance()->_next('pages'); View::newInstance()->_exportVariableToView('page_meta', json_decode($page['s_meta'], true)); return $page; }
public function table($params) { $this->addTableHeader(); $start = ((int) $params['iPage'] - 1) * $params['iDisplayLength']; $this->start = intval($start); $this->limit = intval($params['iDisplayLength']); $pages = Page::newInstance()->listAll(0, null, null, $this->start, $this->limit); $this->processData($pages); $this->total = Page::newInstance()->count(0); $this->total_filtered = $this->total; return $this->getData(); }
function __construct($params) { $this->_get = $params; $p_iPage = 1; if (!is_numeric(Params::getParam('iPage')) || Params::getParam('iPage') < 1) { $this->_get['iPage'] = $p_iPage; Params::setParam('iPage', $p_iPage); } // set start and limit using iPage param $start = ((int) $this->_get['iPage'] - 1) * $this->_get['iDisplayLength']; $this->start = intval($start); $this->limit = intval($this->_get['iDisplayLength']); $this->pages = Page::newInstance()->listAll(0, null, $this->start, $this->limit); $this->total = Page::newInstance()->count(0); $this->total_filtered = $this->total; }
/** * Generates emails from the templates & datas. * - For each emails and for each active locale : * - Check if the emails is empty or does not exists anymore. If so, do nothing. * - Combines templates and datas to produce the s_title and s_text fields. * - Saves those settings for next run. * @return void. */ public function update() { // Decode and transform into a PHP array (true as a second parameter). $data = json_decode(Params::getParam("email_datas", false, false), true); if (!is_array($data)) { mdh_handle_error(sprintf(__("Given JSON datas are not correct (Error #%d)", mdh_current_plugin_name()), json_last_error()), mdh_emailmagick_url()); } // Get the HTML template. $template = Params::getParam("email_template", false, false); // This is current emails datas (stored in the database). $currentDatas = json_decode(osc_get_preference("email_datas", mdh_current_preferences_section()), true); // Create a new array, merge of the old and the new one. $newDatas = array("emails" => array(), "footer" => array("locales" => Madhouse_EmailMagick_Utils::mergeLocales($currentDatas["footer"]["locales"], $data["footer"]["locales"]))); // Iterate through new submitted emails data to update. $i = 0; foreach ($data["emails"] as $e) { // Get the old email datas, as they are right now. $oe = Madhouse_Utils_Collections::findByField($currentDatas["emails"], "s_internal_name", $e["s_internal_name"]); if (is_null($oe)) { // Not found in old emails. => new email has been installed. $locales = $e["locales"]; } else { // Found in old emails. Merge with new locales. $locales = Madhouse_EmailMagick_Utils::mergeLocales($oe["locales"], $e["locales"]); } // Email exists, create in order to be filled and pushed to the new datas (at the end). $nEmail = array("s_internal_name" => $e["s_internal_name"], "locales" => $locales); // Get the email from the database. $email = Page::newInstance()->findByInternalName($e["s_internal_name"]); if ($email !== false && count($email) > 0) { // Update the email. $updated = Madhouse_EmailMagick_Models_Emails::newInstance()->update($template, $email["pk_i_id"], $newDatas, $nEmail); $i += $updated; } array_push($newDatas["emails"], $nEmail); } // Saves the settings. Madhouse_Utils_Controllers::doSettingsPost(array("email_template", "email_datas"), array("email_template" => $template, "email_datas" => json_encode($newDatas)), mdh_emailmagick_url(), null, sprintf(__("Sucessfully updated %d emails (out of %d)!", mdh_current_plugin_name()), $i, count($data["emails"]) * count(osc_get_locales()))); }
function __construct() { parent::__construct(); //specific things for this class $this->pageManager = Page::newInstance(); }
function moreedit_moderate_edit($item_) { $cat_id = $item_['fk_i_category_id']; $item_id = $item_['pk_i_id']; if (osc_get_preference('notify_edit', 'moreedit') == '1') { $aPage = Page::newInstance()->findByInternalName('email_moreedit_notify_edit'); $content = array(); $locale = osc_current_user_locale(); if (isset($aPage['locale'][$locale]['s_title'])) { $content = $aPage['locale'][$locale]; } else { $content = current($aPage['locale']); } $item = Item::newInstance()->findByPrimaryKey($item_id); View::newInstance()->_exportVariableToView('item', $item); $item_url = osc_item_url(); $item_url = '<a href="' . $item_url . '" >' . $item_url . '</a>'; $admin_edit_url = osc_item_admin_edit_url($item['pk_i_id']); $words = array(); $words[] = array('{EDIT_LINK}', '{EDIT_URL}', '{ITEM_DESCRIPTION}', '{ITEM_ID}', '{USER_NAME}', '{USER_EMAIL}', '{WEB_URL}', '{ITEM_TITLE}', '{ITEM_URL}', '{WEB_TITLE}'); $words[] = array('<a href="' . $admin_edit_url . '" >' . $admin_edit_url . '</a>', $admin_edit_url, $item['s_description'], $item['pk_i_id'], $item['s_contact_name'], $item['s_contact_email'], '<a href="' . osc_base_url() . '" >' . osc_base_url() . '</a>', $item['s_title'], $item_url, osc_page_title()); $title = osc_mailBeauty($content['s_title'], $words); $body = osc_mailBeauty($content['s_text'], $words); $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body); osc_sendMail($emailParams); } if (osc_get_preference('moderate_edit', 'moreedit') == '1') { Item::newInstance()->update(array('b_enabled' => 0), array('pk_i_id' => $item_id)); } }
function oc_install_example_data() { require_once LIB_PATH . 'osclass/formatting.php'; require LIB_PATH . 'osclass/installer/basic_data.php'; require_once LIB_PATH . 'osclass/model/Category.php'; $mCat = Category::newInstance(); if (!function_exists('osc_apply_filter')) { function osc_apply_filter($dummyfilter, $str) { return $str; } } foreach ($categories as $category) { $fields['pk_i_id'] = $category['pk_i_id']; $fields['fk_i_parent_id'] = $category['fk_i_parent_id']; $fields['i_position'] = $category['i_position']; $fields['i_expiration_days'] = 0; $fields['b_enabled'] = 1; $aFieldsDescription[osc_current_admin_locale()]['s_name'] = $category['s_name']; $mCat->insert($fields, $aFieldsDescription); } require_once LIB_PATH . 'osclass/model/Item.php'; require_once LIB_PATH . 'osclass/model/ItemComment.php'; require_once LIB_PATH . 'osclass/model/ItemLocation.php'; require_once LIB_PATH . 'osclass/model/ItemResource.php'; require_once LIB_PATH . 'osclass/model/ItemStats.php'; require_once LIB_PATH . 'osclass/model/User.php'; require_once LIB_PATH . 'osclass/model/Country.php'; require_once LIB_PATH . 'osclass/model/Region.php'; require_once LIB_PATH . 'osclass/model/City.php'; require_once LIB_PATH . 'osclass/model/CityArea.php'; require_once LIB_PATH . 'osclass/model/Field.php'; require_once LIB_PATH . 'osclass/model/Page.php'; require_once LIB_PATH . 'osclass/model/Log.php'; require_once LIB_PATH . 'osclass/model/CategoryStats.php'; require_once LIB_PATH . 'osclass/model/CountryStats.php'; require_once LIB_PATH . 'osclass/model/RegionStats.php'; require_once LIB_PATH . 'osclass/model/CityStats.php'; require_once LIB_PATH . 'osclass/helpers/hSecurity.php'; require_once LIB_PATH . 'osclass/helpers/hValidate.php'; require_once LIB_PATH . 'osclass/helpers/hUsers.php'; require_once LIB_PATH . 'osclass/ItemActions.php'; $mItem = new ItemActions(true); foreach ($item as $k => $v) { if ($k == 'description' || $k == 'title') { Params::setParam($k, array(osc_current_admin_locale() => $v)); } else { Params::setParam($k, $v); } } $mItem->prepareData(true); $successItem = $mItem->add(); $successPageresult = Page::newInstance()->insert(array('s_internal_name' => $page['s_internal_name'], 'b_indelible' => 0, 's_meta' => json_encode('')), array(osc_current_admin_locale() => array('s_title' => $page['s_title'], 's_text' => $page['s_text']))); }
function __construct() { parent::__construct(); $this->pageManager = Page::newInstance(); }
/** * Let you know if there are more static pages in the list. If static pages are not loaded, this function will load them. * * @return <boolean> */ function osc_has_static_pages() { if (!View::newInstance()->_exists('pages')) { View::newInstance()->_exportVariableToView('pages', Page::newInstance()->listAll(false)); } return View::newInstance()->_next('pages'); }
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 'userajax': // This is the autocomplete AJAX $users = User::newInstance()->ajax(Params::getParam("term")); if (count($users) == 0) { echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results')))); } else { echo json_encode($users); } break; case 'date_format': echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date('Y-m-d H:i:s'), Params::getParam('format')))); 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_admin_' . $hook); break; } break; case 'categories_order': // Save the order of the categories osc_csrf_check(false); $aIds = Params::getParam('list'); $orderParent = 0; $orderSub = 0; $catParent = 0; $error = 0; $catManager = Category::newInstance(); $aRecountCat = array(); foreach ($aIds as $id => $parent) { if ($parent == 'root') { $res = $catManager->updateOrder($id, $orderParent); if (is_bool($res) && !$res) { $error = 1; } // find category $auxCategory = Category::newInstance()->findByPrimaryKey($id); // set parent category $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = NULL; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok $parentId = $auxCategory['fk_i_parent_id']; if ($parentId) { // update parent category stats array_push($aRecountCat, $id); array_push($aRecountCat, $parentId); } } } $orderParent++; } else { if ($parent != $catParent) { $catParent = $parent; $orderSub = 0; } $res = $catManager->updateOrder($id, $orderSub); if (is_bool($res) && !$res) { $error = 1; } // set parent category $auxCategory = Category::newInstance()->findByPrimaryKey($id); $auxCategoryP = Category::newInstance()->findByPrimaryKey($catParent); $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = $catParent; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok // update category parent $prevParentId = $auxCategory['fk_i_parent_id']; $parentId = $auxCategoryP['pk_i_id']; array_push($aRecountCat, $prevParentId); array_push($aRecountCat, $parentId); } } $orderSub++; } } // update category stats foreach ($aRecountCat as $rId) { osc_update_cat_stats_id($rId); } if ($error) { $result = array('error' => __("An error occurred")); } else { $result = array('ok' => __("Order saved")); } echo json_encode($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': osc_csrf_check(false); $error = 0; $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")) { // remove categories from a field Field::newInstance()->cleanCategoriesFromField(Params::getParam("id")); // no error... continue updating fields if ($error == 0) { $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name"); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } // trim options $s_options = ''; $aux = Params::getParam('s_options'); $aAux = explode(',', $aux); foreach ($aAux as &$option) { $option = trim($option); } $s_options = implode(',', $aAux); $res = 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' => $s_options), array('pk_i_id' => Params::getParam("id"))); if (is_bool($res) && !$res) { $error = 1; } } // no error... continue inserting categories-field if ($error == 0) { $aCategories = Params::getParam("categories"); if (is_array($aCategories) && count($aCategories) > 0) { $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories); if (!$res) { $error = 1; } } } // error while updating? if ($error == 1) { $message = __("An error occurred while updating."); } } else { $error = 1; $message = __("Sorry, you already have a field with that name"); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => Params::getParam("id")); } echo json_encode($result); break; case 'delete_field': osc_csrf_check(false); $res = Field::newInstance()->deleteByPrimaryKey(Params::getParam('id')); if ($res > 0) { $result = array('ok' => __('The custom field has been deleted')); } else { $result = array('error' => __('An error occurred while deleting')); } echo json_encode($result); break; case 'add_field': osc_csrf_check(false); $s_name = __('NEW custom field'); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $fieldManager = Field::newInstance(); $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array()); if ($result) { echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name)); } else { echo json_encode(array('error' => 1)); } break; case 'enable_category': osc_csrf_check(false); $id = strip_tags(Params::getParam('id')); $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0; $error = 0; $result = array(); $aUpdated = array(); $mCategory = Category::newInstance(); $aCategory = $mCategory->findByPrimaryKey($id); if ($aCategory == false) { $result = array('error' => sprintf(__("No category with id %d exists"), $id)); echo json_encode($result); break; } // root category if ($aCategory['fk_i_parent_id'] == '') { $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id)); $subCategories = $mCategory->findSubcategories($id); $aIds = array($id); $aUpdated[] = array('id' => $id); foreach ($subCategories as $subcategory) { $aIds[] = $subcategory['pk_i_id']; $aUpdated[] = array('id' => $subcategory['pk_i_id']); } Item::newInstance()->enableByCategory($enabled, $aIds); if ($enabled) { $result = array('ok' => __('The category as well as its subcategories have been enabled')); } else { $result = array('ok' => __('The category as well as its subcategories have been disabled')); } $result['affectedIds'] = $aUpdated; echo json_encode($result); break; } // subcategory $parentCategory = $mCategory->findRootCategory($id); if (!$parentCategory['b_enabled']) { $result = array('error' => __('Parent category is disabled, you can not enable that category')); echo json_encode($result); break; } $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); if ($enabled) { $result = array('ok' => __('The subcategory has been enabled')); } else { $result = array('ok' => __('The subcategory has been disabled')); } $result['affectedIds'] = array(array('id' => $id)); echo json_encode($result); break; case 'delete_category': osc_csrf_check(false); $id = Params::getParam("id"); $error = 0; $categoryManager = Category::newInstance(); $res = $categoryManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The categories have been deleted'); } else { $error = 1; $message = __('An error occurred while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($result); break; case 'edit_category_post': osc_csrf_check(false); $id = Params::getParam("id"); $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0; $error = 0; $has_one_title = 0; $postParams = Params::getParamsAsArray(); foreach ($postParams as $k => $v) { if (preg_match('|(.+?)#(.+)|', $k, $m)) { if ($m[2] == 's_name') { if ($v != "") { $has_one_title = 1; $aFieldsDescription[$m[1]][$m[2]] = $v; $s_text = $v; } else { $aFieldsDescription[$m[1]][$m[2]] = NULL; $error = 1; } } else { $aFieldsDescription[$m[1]][$m[2]] = $v; } } } $l = osc_language(); if ($error == 0 || $error == 1 && $has_one_title == 1) { $categoryManager = Category::newInstance(); $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id); $categoryManager->updateExpiration($id, $fields['i_expiration_days']); if (is_bool($res)) { $error = 2; } } if (Params::getParam('apply_changes_to_subcategories') == 1) { $subcategories = $categoryManager->findSubcategories($id); foreach ($subcategories as $subc) { $categoryManager->updateExpiration($subc['pk_i_id'], $fields['i_expiration_days']); } } if ($error == 0) { $msg = __("Category updated correctly"); } else { if ($error == 1) { if ($has_one_title == 1) { $error = 4; $msg = __('Category updated correctly, but some titles are empty'); } else { $msg = __('Sorry, including at least a title is mandatory'); } } else { if ($error == 2) { $msg = __('An error occurred while updating'); } } } echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name'])); break; case 'custom': // Execute via AJAX custom file $ajaxFile = Params::getParam("ajaxfile"); if ($ajaxFile == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (stripos($ajaxFile, '../') !== false) { echo json_encode(array('error' => 'no valid ajaxFile')); break; } if (!file_exists(osc_plugins_path() . $ajaxFile)) { echo json_encode(array('error' => "ajaxFile doesn't exist")); break; } require_once osc_plugins_path() . $ajaxFile; break; case 'test_mail': $title = sprintf(__('Test email, %s'), 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 occurred while sending email')); } echo json_encode($array); break; case 'test_mail_template': // replace por valores por defecto $email = Params::getParam("email"); $title = Params::getParam("title"); $body = urldecode(Params::getParam("body")); $emailParams = array('subject' => $title, 'to' => $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 occurred while sending email')); } echo json_encode($array); break; case 'order_pages': osc_csrf_check(false); $order = Params::getParam("order"); $id = Params::getParam("id"); 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') { $page = $mPages->findPrevPage($actual_order); } else { if ($order == 'down') { $page = $mPages->findNextPage($actual_order); } } if (isset($page['i_order'])) { $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id)); $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id'])); } } break; /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ case 'upgrade': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(false); $message = ""; $error = 0; $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 **** ***********************/ $data = osc_file_get_contents("http://osclass.org/latest_version.php"); $data = json_decode(substr($data, 1, strlen($data) - 3), true); $source_file = $data['url']; if ($source_file != '') { $tmp = explode("/", $source_file); $filename = end($tmp); $result = osc_downloadFile($source_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); //TRY TO REMOVE THE ZIP PACKAGE @unlink(osc_content_path() . 'downloads/' . $filename); if ($fail == 0) { // Everything is OK, 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 = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $error_queries = $comm->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 looks good! Your Osclass installation is up-to-date'); } else { $message = __('Nearly everything looks good! Your Osclass installation is up-to-date, but there were some errors removing temporary files. Please manually remove the "oc-temp" folder'); $error = 6; // Some errors removing files } } else { $sql_error_msg = $error_queries[2]; $message = __('Problems when upgrading the database'); $error = 5; // Problems upgrading the database } } else { $message = __('Problems when copying files. Please check your permissions. '); $error = 4; // Problems copying files. Maybe permissions are not correct } } else { $message = __('Nothing to copy'); $error = 99; // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't 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 ($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; /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ case 'market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(false); $section = Params::getParam('section'); $code = Params::getParam('code'); $plugin = false; $re_enable = false; $message = ""; $error = 0; $data = array(); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $url = osc_market_url($section, $code); $data = json_decode(osc_file_get_contents($url), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $data = json_decode(osc_file_get_contents($code), true); } else { echo json_encode(array('error' => 8, 'error_msg' => __('No external sources are allowed'))); break; } } /*********************** **** DOWNLOAD FILE **** ***********************/ if (isset($data['s_update_url']) && isset($data['s_source_file']) && isset($data['e_type'])) { if ($data['e_type'] == 'THEME') { $folder = 'themes/'; } else { if ($data['e_type'] == 'LANGUAGE') { $folder = 'languages/'; } else { // PLUGINS $folder = 'plugins/'; $plugin = Plugins::findByUpdateURI($data['s_update_url']); if ($plugin != false) { if (Plugins::isEnabled($plugin)) { Plugins::runHook($plugin . '_disable'); Plugins::deactivate($plugin); $re_enable = true; } } } } $filename = $data['s_update_url'] . "_" . $data['s_version'] . ".zip"; $url_source_file = $data['s_source_file']; // error_log('Source file: ' . $url_source_file); // error_log('Filename: ' . $filename); $result = osc_downloadFile($url_source_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, osc_content_path() . 'downloads/oc-temp/'); if ($res == 1) { // Everything is OK, continue /********************** ***** COPY FILES ***** **********************/ $fail = -1; if ($handle = opendir(osc_content_path() . 'downloads/oc-temp')) { $folder_dest = ABS_PATH . "oc-content/" . $folder; if (function_exists('posix_getpwuid')) { $current_user = posix_getpwuid(posix_geteuid()); $ownerFolder = posix_getpwuid(fileowner($folder_dest)); } $fail = 0; while (false !== ($_file = readdir($handle))) { if ($_file != '.' && $_file != '..') { $copyprocess = osc_copy(osc_content_path() . "downloads/oc-temp/" . $_file, $folder_dest . $_file); if ($copyprocess == false) { $fail = 1; } } } closedir($handle); // Additional actions is not important for the rest of the proccess // We will inform the user of the problems but the upgrade could continue // Also remove the zip package /**************************** ** REMOVE TEMPORARY FILES ** ****************************/ @unlink(osc_content_path() . 'downloads/' . $filename); $path = osc_content_path() . 'downloads/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 ($fail == 0) { // Everything is OK, continue if ($data['e_type'] != 'THEME' && $data['e_type'] != 'LANGUAGE') { if ($plugin != false && $re_enable) { $enabled = Plugins::activate($plugin); if ($enabled) { Plugins::runHook($plugin . '_enable'); } } } // recount plugins&themes for update if ($section == 'plugins') { osc_check_plugins_update(true); } else { if ($section == 'themes') { osc_check_themes_update(true); } else { if ($section == 'languages') { // load oc-content/ if (osc_checkLocales()) { $message .= __('The language has been installed correctly'); } else { $message .= __('There was a problem adding the language'); $error = 8; } osc_check_languages_update(true); } } } if ($rm_errors == 0) { $message = __('Everything looks good!'); $error = 0; } else { $message = __('Nearly everything looks good! but there were some errors removing temporary files. Please manually remove the \\"oc-temp\\" folder'); $error = 6; // Some errors removing files } } else { $message = __('Problems when copying files. Please check your permissions. '); if ($current_user['uid'] != $ownerFolder['uid']) { if (function_exists('posix_getgrgid')) { $current_group = posix_getgrgid($current_user['gid']); $message .= '<p><strong>' . sprintf(__('NOTE: Web user and destination folder user is not the same, you might have an issue there. <br/>Do this in your console:<br/>chown -R %s:%s %s'), $current_user['name'], $current_group['name'], $folder_dest) . '</strong></p>'; } } $error = 4; // Problems copying files. Maybe permissions are not correct } } else { $message = __('Nothing to copy'); $error = 99; // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file! } } else { $message = __('Unzip failed'); $error = 3; // Unzip failed } } else { $message = __('Download failed'); $error = 2; // Download failed } } else { $message = __('Input code not valid'); $error = 7; // Input code not valid } } else { $message = __('Missing download URL'); $error = 1; // Missing download URL } echo json_encode(array('error' => $error, 'message' => $message, 'data' => $data)); break; case 'check_market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT $section = Params::getParam('section'); $code = Params::getParam('code'); $data = array(); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $data = json_decode(osc_file_get_contents(osc_market_url($section, $code)), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $data = json_decode(osc_file_get_contents($code), true); } else { echo json_encode(array('error' => 3, 'error_msg' => __('No external sources are allowed'))); break; } } if (!isset($data['s_source_file']) || !isset($data['s_update_url'])) { $data = array('error' => 2, 'error_msg' => __('Invalid code')); } } else { $data = array('error' => 1, 'error_msg' => __('No code was submitted')); } echo json_encode($data); break; case 'market_data': $section = Params::getParam('section'); $page = Params::getParam("mPage"); $featured = Params::getParam("featured"); $sort = Params::getParam("sort"); $order = Params::getParam("order"); // for the moment this value is static $length = 9; if ($page >= 1) { $page--; } $url = osc_market_url($section) . "page/" . $page . '/'; if ($length != '' && is_numeric($length)) { $url .= 'length/' . $length . '/'; } if ($sort != '') { $url .= 'order/' . $sort; if ($order != '') { $url .= '/' . $order; } } if ($featured != '') { $url = osc_market_featured_url($section); } $data = array(); $data = json_decode(osc_file_get_contents($url), true); if (!isset($data[$section])) { $data = array('error' => 1, 'error_msg' => __('No market data')); } echo 'var market_data = window.market_data || {}; market_data.' . $section . ' = ' . json_encode($data) . ';'; break; case 'local_market': // AVOID CROSS DOMAIN PROBLEMS OF AJAX REQUEST $marketPage = Params::getParam("mPage"); if ($marketPage >= 1) { $marketPage--; } $out = osc_file_get_contents(osc_market_url(Params::getParam("section")) . "page/" . $marketPage); $array = json_decode($out, true); // do pagination $pageActual = $array['page']; $totalPages = ceil($array['total'] / $array['sizePage']); $params = array('total' => $totalPages, 'selected' => $pageActual, 'url' => '#{PAGE}', 'sides' => 5); // set pagination $pagination = new Pagination($params); $aux = $pagination->doPagination(); $array['pagination_content'] = $aux; // encode to json echo json_encode($array); break; case 'dashboardbox_market': $error = 0; // make market call $url = getPreference('marketURL') . 'dashboardbox/'; $content = ''; if (false === ($json = @osc_file_get_contents($url))) { $error = 1; } else { $content = $json; } if ($error == 1) { echo json_encode(array('error' => 1)); } else { // replace content with correct urls $content = str_replace('{URL_MARKET_THEMES}', osc_admin_base_url(true) . '?page=market&action=themes', $content); $content = str_replace('{URL_MARKET_PLUGINS}', osc_admin_base_url(true) . '?page=market&action=plugins', $content); echo json_encode(array('html' => $content)); } break; case 'location_stats': osc_csrf_check(false); $workToDo = osc_update_location_stats(); if ($workToDo > 0) { $array['status'] = 'more'; $array['pending'] = $workToDo; echo json_encode($array); } else { $array['status'] = 'done'; echo json_encode($array); } break; case 'error_permissions': echo json_encode(array('error' => __("You don't have the necessary permissions"))); break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
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; } }
/** * Remove data and tables related to the plugin. */ public function uninstall() { Page::newInstance()->deleteByInternalName('email_moreedit_notify_edit'); }
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 'userajax': // This is the autocomplete AJAX $users = User::newInstance()->ajax(Params::getParam("term")); if (count($users) == 0) { echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results')))); } else { echo json_encode($users); } break; case 'date_format': echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date('Y-m-d H:i:s'), Params::getParam('format')))); 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_admin_' . $hook); break; } break; case 'categories_order': // Save the order of the categories osc_csrf_check(false); $aIds = Params::getParam('list'); $order = array(); $error = 0; $catManager = Category::newInstance(); $aRecountCat = array(); foreach ($aIds as $cat) { if (!isset($order[$cat['p']])) { $order[$cat['p']] = 0; } $res = $catManager->update(array('fk_i_parent_id' => $cat['p'] == 'root' ? NULL : $cat['p'], 'i_position' => $order[$cat['p']]), array('pk_i_id' => $cat['c'])); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { $aRecountCat[] = $cat['c']; } } $order[$cat['p']] = $order[$cat['p']] + 1; } // update category stats foreach ($aRecountCat as $rId) { osc_update_cat_stats_id($rId); } if ($error) { $result = array('error' => __("An error occurred")); } else { $result = array('ok' => __("Order saved")); } echo json_encode($result); break; case 'category_edit_iframe': $this->_exportVariableToView('category', Category::newInstance()->findByPrimaryKey(Params::getParam("id"), 'all')); if (count(Category::newInstance()->findSubcategories(Params::getParam("id"))) > 0) { $this->_exportVariableToView('has_subcategories', true); } else { $this->_exportVariableToView('has_subcategories', false); } $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': osc_csrf_check(false); $error = 0; $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")) { // remove categories from a field Field::newInstance()->cleanCategoriesFromField(Params::getParam("id")); // no error... continue updating fields if ($error == 0) { $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name"); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } // trim options $s_options = ''; $aux = Params::getParam('s_options'); $aAux = explode(',', $aux); foreach ($aAux as &$option) { $option = trim($option); } $s_options = implode(',', $aAux); $res = 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, 'b_searchable' => Params::getParam("field_searchable") == "1" ? 1 : 0, 's_options' => $s_options), array('pk_i_id' => Params::getParam("id"))); if (is_bool($res) && !$res) { $error = 1; } } // no error... continue inserting categories-field if ($error == 0) { $aCategories = Params::getParam("categories"); if (is_array($aCategories) && count($aCategories) > 0) { $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories); if (!$res) { $error = 1; } } } // error while updating? if ($error == 1) { $message = __("An error occurred while updating."); } } else { $error = 1; $message = __("Sorry, you already have a field with that name"); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => Params::getParam("id")); } echo json_encode($result); break; case 'delete_field': osc_csrf_check(false); $res = Field::newInstance()->deleteByPrimaryKey(Params::getParam('id')); if ($res > 0) { $result = array('ok' => __('The custom field has been deleted')); } else { $result = array('error' => __('An error occurred while deleting')); } echo json_encode($result); break; case 'add_field': osc_csrf_check(false); $s_name = __('NEW custom field'); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $fieldManager = Field::newInstance(); $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array()); if ($result) { echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name)); } else { echo json_encode(array('error' => 1)); } break; case 'enable_category': osc_csrf_check(false); $id = strip_tags(Params::getParam('id')); $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0; $error = 0; $result = array(); $aUpdated = array(); $mCategory = Category::newInstance(); $aCategory = $mCategory->findByPrimaryKey($id); if ($aCategory == false) { $result = array('error' => sprintf(__("No category with id %d exists"), $id)); echo json_encode($result); break; } // root category if ($aCategory['fk_i_parent_id'] == '') { $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id)); $subCategories = $mCategory->findSubcategories($id); $aIds = array($id); $aUpdated[] = array('id' => $id); foreach ($subCategories as $subcategory) { $aIds[] = $subcategory['pk_i_id']; $aUpdated[] = array('id' => $subcategory['pk_i_id']); } Item::newInstance()->enableByCategory($enabled, $aIds); if ($enabled) { $result = array('ok' => __('The category as well as its subcategories have been enabled')); } else { $result = array('ok' => __('The category as well as its subcategories have been disabled')); } $result['affectedIds'] = $aUpdated; echo json_encode($result); break; } // subcategory $parentCategory = $mCategory->findRootCategory($id); if (!$parentCategory['b_enabled']) { $result = array('error' => __('Parent category is disabled, you can not enable that category')); echo json_encode($result); break; } $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); if ($enabled) { $result = array('ok' => __('The subcategory has been enabled')); } else { $result = array('ok' => __('The subcategory has been disabled')); } $result['affectedIds'] = array(array('id' => $id)); echo json_encode($result); break; case 'delete_category': osc_csrf_check(false); $id = Params::getParam("id"); $error = 0; $categoryManager = Category::newInstance(); $res = $categoryManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The categories have been deleted'); } else { $error = 1; $message = __('An error occurred while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($result); break; case 'edit_category_post': osc_csrf_check(false); $id = Params::getParam("id"); $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0; $fields['b_price_enabled'] = Params::getParam('b_price_enabled') != '' ? 1 : 0; $apply_changes_to_subcategories = Params::getParam('apply_changes_to_subcategories') == 1 ? true : false; $error = 0; $has_one_title = 0; $postParams = Params::getParamsAsArray(); foreach ($postParams as $k => $v) { if (preg_match('|(.+?)#(.+)|', $k, $m)) { if ($m[2] == 's_name') { if ($v != "") { $has_one_title = 1; $aFieldsDescription[$m[1]][$m[2]] = $v; $s_text = $v; } else { $aFieldsDescription[$m[1]][$m[2]] = NULL; $error = 1; } } else { $aFieldsDescription[$m[1]][$m[2]] = $v; } } } $l = osc_language(); if ($error == 0 || $error == 1 && $has_one_title == 1) { $categoryManager = Category::newInstance(); $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id); $categoryManager->updateExpiration($id, $fields['i_expiration_days'], $apply_changes_to_subcategories); $categoryManager->updatePriceEnabled($id, $fields['b_price_enabled'], $apply_changes_to_subcategories); if (is_bool($res)) { $error = 2; } } if ($error == 0) { $msg = __("Category updated correctly"); } else { if ($error == 1) { if ($has_one_title == 1) { $error = 4; $msg = __('Category updated correctly, but some titles are empty'); } else { $msg = __('Sorry, including at least a title is mandatory'); } } else { if ($error == 2) { $msg = __('An error occurred while updating'); } } } echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name'])); 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 { $file = Params::getParam("ajaxfile"); } if ($file == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (stripos($file, '../') !== false || stripos($file, '..\\') !== false) { echo json_encode(array('error' => 'no valid file')); break; } if (!file_exists(osc_plugins_path() . $file)) { echo json_encode(array('error' => "file doesn't exist")); break; } require_once osc_plugins_path() . $file; break; case 'test_mail': $title = sprintf(__('Test email, %s'), 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 occurred while sending email')); } echo json_encode($array); break; case 'test_mail_template': // replace por valores por defecto $email = Params::getParam("email"); $title = Params::getParam("title"); $body = Params::getParam("body", false, false); $emailParams = array('subject' => $title, 'to' => $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 occurred while sending email')); } echo json_encode($array); break; case 'order_pages': osc_csrf_check(false); $order = Params::getParam("order"); $id = Params::getParam("id"); 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') { $page = $mPages->findPrevPage($actual_order); } else { if ($order == 'down') { $page = $mPages->findNextPage($actual_order); } } if (isset($page['i_order'])) { $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id)); $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id'])); } } break; case 'check_version': $data = osc_file_get_contents('http://osclass.org/latest_version_v1.php?callback=?'); $data = preg_replace('|^\\?\\((.*?)\\);$|', '$01', $data); $json = json_decode($data); if (isset($json->version)) { if ($json->version > osc_version()) { osc_set_preference('update_core_json', $data); echo json_encode(array('error' => 0, 'msg' => __('Update available'))); } else { osc_set_preference('update_core_json', ''); echo json_encode(array('error' => 0, 'msg' => __('No update available'))); } osc_set_preference('last_version_check', time()); } else { // Latest version couldn't be checked (site down?) osc_set_preference('last_version_check', time() - 82800); // 82800 = 23 hours, so repeat check in one hour echo json_encode(array('error' => 1, 'msg' => __('Version could not be checked'))); } break; case 'check_languages': $total = _osc_check_languages_update(); echo json_encode(array('msg' => __('Checked updates'), 'total' => $total)); break; case 'check_themes': $total = _osc_check_themes_update(); echo json_encode(array('msg' => __('Checked updates'), 'total' => $total)); break; case 'check_plugins': $total = _osc_check_plugins_update(); echo json_encode(array('msg' => __('Checked updates'), 'total' => $total)); break; /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ case 'upgrade': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(); $result = osc_do_upgrade(); if (!defined('__FROM_CRON__') || !__FROM_CRON__) { if ($result['error'] == 0) { osc_add_flash_ok_message($result['message'], 'admin'); } else { if ($result['error'] == 6) { osc_add_flash_warning_message($result['message'], 'admin'); } } } echo json_encode($result); break; /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ case 'market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(false); $result = osc_market(Params::getParam('section'), Params::getParam('code')); echo json_encode($result); break; case 'check_market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT $section = Params::getParam('section'); $code = Params::getParam('code'); $data = array(); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $data = json_decode(osc_file_get_contents(osc_market_url($section, $code), array('api_key' => osc_market_api_connect())), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $data = json_decode(osc_file_get_contents($code), true); } else { echo json_encode(array('error' => 3, 'error_msg' => __('No external sources are allowed'))); break; } } if (!isset($data['s_source_file']) || !isset($data['s_update_url'])) { //$data = array('error' => 2, 'error_msg' => __('Invalid code')); } } else { $data = array('error' => 1, 'error_msg' => __('No code was submitted')); } echo json_encode($data); break; case 'market_data': $section = Params::getParam('section'); $page = Params::getParam("mPage"); $featured = Params::getParam("featured"); $sort = Params::getParam("sort"); $order = Params::getParam("order"); // for the moment this value is static $length = 9; if ($page >= 1) { $page--; } $url = osc_market_url($section) . "page/" . $page . '/'; if ($length != '' && is_numeric($length)) { $url .= 'length/' . $length . '/'; } if ($sort != '') { $url .= 'order/' . $sort; if ($order != '') { $url .= '/' . $order; } } if ($featured != '') { $url = osc_market_featured_url($section); } $data = array(); $data = json_decode(osc_file_get_contents($url, array('api_key' => osc_market_api_connect())), true); if (!isset($data[$section])) { $data = array('error' => 1, 'error_msg' => __('No market data')); } echo 'var market_data = window.market_data || {}; market_data.' . $section . ' = ' . json_encode($data) . ';'; break; case 'local_market': // AVOID CROSS DOMAIN PROBLEMS OF AJAX REQUEST $marketPage = Params::getParam("mPage"); if ($marketPage >= 1) { $marketPage--; } $out = osc_file_get_contents(osc_market_url(Params::getParam("section")) . "page/" . $marketPage, array('api_key' => osc_market_api_connect())); $array = json_decode($out, true); // do pagination $pageActual = $array['page']; $totalPages = ceil($array['total'] / $array['sizePage']); $params = array('total' => $totalPages, 'selected' => $pageActual, 'url' => '#{PAGE}', 'sides' => 5); // set pagination $pagination = new Pagination($params); $aux = $pagination->doPagination(); $array['pagination_content'] = $aux; // encode to json echo json_encode($array); break; case 'market_connect': $json = osc_file_get_contents(osc_market_url() . 'connect/', array('s_email' => Params::getParam('s_email'), 's_password' => Params::getParam('s_password'))); $data = json_decode($json, true); if ($data['error'] == 0) { osc_set_preference('marketAPIConnect', $data['api_key']); unset($data['api_key']); $json = json_encode($data); } echo $json; break; case 'dashboardbox_market': $error = 0; // make market call $url = osc_get_preference('marketURL') . 'dashboardbox/'; $content = ''; if (false === ($json = @osc_file_get_contents($url))) { $error = 1; } else { $content = $json; } if ($error == 1) { echo json_encode(array('error' => 1)); } else { // replace content with correct urls $content = str_replace('{URL_MARKET_THEMES}', osc_admin_base_url(true) . '?page=market&action=themes', $content); $content = str_replace('{URL_MARKET_PLUGINS}', osc_admin_base_url(true) . '?page=market&action=plugins', $content); echo json_encode(array('html' => $content)); } break; case 'market_header': $error = 0; // make market call $url = osc_get_preference('marketURL') . 'market_header/'; $content = ''; if (false === ($json = @osc_file_get_contents($url))) { $error = 1; } else { $content = $json; } if ($error == 1) { echo json_encode(array('error' => 1)); } else { echo json_encode(array('html' => $content)); } break; case 'location_stats': osc_csrf_check(false); $workToDo = osc_update_location_stats(); if ($workToDo > 0) { $array['status'] = 'more'; $array['pending'] = $workToDo; echo json_encode($array); } else { $array['status'] = 'done'; echo json_encode($array); } break; case 'country_slug': $exists = Country::newInstance()->findBySlug(Params::getParam('slug')); if (isset($exists['s_slug'])) { echo json_encode(array('error' => 1, 'country' => $exists)); } else { echo json_encode(array('error' => 0)); } break; case 'region_slug': $exists = Region::newInstance()->findBySlug(Params::getParam('slug')); if (isset($exists['s_slug'])) { echo json_encode(array('error' => 1, 'region' => $exists)); } else { echo json_encode(array('error' => 0)); } break; case 'city_slug': $exists = City::newInstance()->findBySlug(Params::getParam('slug')); if (isset($exists['s_slug'])) { echo json_encode(array('error' => 1, 'city' => $exists)); } else { echo json_encode(array('error' => 0)); } break; case 'error_permissions': echo json_encode(array('error' => __("You don't have the necessary permissions"))); break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
public function uninstall() { $confPath = PAYMENT_PRO_PATH . 'payments/'; $dir = opendir($confPath); while ($file = readdir($dir)) { if (is_dir($confPath . $file) && $file != '.' && $file != '..') { if (file_exists($confPath . $file . '/load.php')) { include_once $confPath . $file . '/load.php'; } } } closedir($dir); osc_run_hook('payment_pro_pre_uninstall'); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_premium())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_publish())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_wallet())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_prices())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_invoice_row())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_invoice())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_pending_row())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_mail_queue())); $page = Page::newInstance()->findByInternalName('payment_pro_email_payment'); Page::newInstance()->deleteByPrimaryKey($page['pk_i_id']); Preference::newInstance()->delete(array('s_section' => 'payment_pro')); osc_run_hook('payment_pro_post_uninstall'); }
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(); }
function doModel() { switch ($this->action) { case 'login_post': //post execution for the login $admin = Admin::newInstance()->findByUsername(Params::getParam('user')); if ($admin) { if ($admin["s_password"] == sha1(Params::getParam('password'))) { if (Params::getParam('remember')) { //this include contains de osc_genRandomPassword function require_once osc_lib_path() . 'osclass/helpers/hSecurity.php'; $secret = osc_genRandomPassword(); Admin::newInstance()->update(array('s_secret' => $secret), array('pk_i_id' => $admin['pk_i_id'])); Cookie::newInstance()->set_expires(osc_time_cookie()); Cookie::newInstance()->push('oc_adminId', $admin['pk_i_id']); Cookie::newInstance()->push('oc_adminSecret', $secret); Cookie::newInstance()->push('oc_adminLocale', Params::getParam('locale')); Cookie::newInstance()->set(); } //we are logged in... let's go! Session::newInstance()->_set('adminId', $admin['pk_i_id']); Session::newInstance()->_set('adminUserName', $admin['s_username']); Session::newInstance()->_set('adminName', $admin['s_name']); Session::newInstance()->_set('adminEmail', $admin['s_email']); Session::newInstance()->_set('adminLocale', Params::getParam('locale')); } else { osc_add_flash_message(_m('The password is incorrect'), 'admin'); } } else { osc_add_flash_message(_m('That username does not exist'), 'admin'); } //returning logged in to the main page... $this->redirectTo(osc_admin_base_url()); break; case 'recover': //form to recover the password (in this case we have the form in /gui/) //#dev.conquer: we cannot use the doView here and only here $this->doView('gui/recover.php'); break; case 'recover_post': //post execution to recover the password $admin = Admin::newInstance()->findByEmail(Params::getParam('email')); if ($admin) { if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) { if (!osc_check_recaptcha()) { osc_add_flash_message(_m('The Recaptcha code is wrong'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=login&action=recover'); return false; // BREAK THE PROCESS, THE RECAPTCHA IS WRONG } } require_once osc_lib_path() . 'osclass/helpers/hSecurity.php'; $newPassword = osc_genRandomPassword(40); Admin::newInstance()->update(array('s_secret' => $newPassword), array('pk_i_id' => $admin['pk_i_id'])); $password_link = osc_forgot_admin_password_confirm_url($admin['pk_i_id'], $newPassword); $aPage = Page::newInstance()->findByInternalName('email_user_forgot_password'); $content = array(); $locale = osc_current_user_locale(); if (isset($aPage['locale'][$locale]['s_title'])) { $content = $aPage['locale'][$locale]; } else { $content = current($aPage['locale']); } if (!is_null($content)) { $words = array(); $words[] = array('{USER_NAME}', '{USER_EMAIL}', '{WEB_TITLE}', '{IP_ADDRESS}', '{PASSWORD_LINK}', '{DATE_TIME}'); $words[] = array($admin['s_name'], $admin['s_email'], osc_page_title(), $_SERVER['REMOTE_ADDR'], $password_link, date(osc_time_format() . ' ' . osc_date_format())); $title = osc_mailBeauty($content['s_title'], $words); $body = osc_mailBeauty($content['s_text'], $words); $emailParams = array('subject' => $title, 'to' => $admin['s_email'], 'to_name' => $admin['s_name'], 'body' => $body, 'alt_body' => $body); osc_sendMail($emailParams); } } osc_add_flash_message(_m('A new password has been sent to your e-mail'), 'admin'); $this->redirectTo(osc_admin_base_url()); break; case 'forgot': //form to recover the password (in this case we have the form in /gui/) $admin = Admin::newInstance()->findByIdSecret(Params::getParam('adminId'), Params::getParam('code')); if ($admin) { $this->doView('gui/forgot_password.php'); } else { osc_add_flash_message(_m('Sorry, the link is not valid'), 'admin'); $this->redirectTo(osc_admin_base_url()); } break; case 'forgot_post': $admin = Admin::newInstance()->findByIdSecret(Params::getParam('adminId'), Params::getParam('code')); if ($admin) { if (Params::getParam('new_password') == Params::getParam('new_password2')) { Admin::newInstance()->update(array('s_secret' => osc_genRandomPassword(), 's_password' => sha1(Params::getParam('new_password'))), array('pk_i_id' => $admin['pk_i_id'])); osc_add_flash_message(_m('The password has been changed'), 'admin'); $this->redirectTo(osc_admin_base_url()); } else { osc_add_flash_message(_m('Error, the password don\'t match'), 'admin'); $this->redirectTo(osc_forgot_admin_password_confirm_url(Params::getParam('adminId'), Params::getParam('code'))); } } else { osc_add_flash_message(_m('Sorry, the link is not valid'), 'admin'); } $this->redirectTo(osc_admin_base_url()); break; } }
function allSeo_call_after_uninstall() { ModelSeo::newInstance()->uninstall(); ModelSeoPage::newInstance()->uninstall(); ModelSeoLink::newInstance()->uninstall(); ModelSeoCategory::newInstance()->uninstall(); osc_delete_preference('allSeo_description', 'plugin-all_in_one'); osc_delete_preference('allSeo_keywords', 'plugin-all_in_one'); osc_delete_preference('allSeo_title_first', 'plugin-all_in_one'); osc_delete_preference('allSeo_robots', 'plugin-all_in_one'); osc_delete_preference('allSeo_robots_enabled', 'plugin-all_in_one'); osc_delete_preference('allSeo_htaccess', 'plugin-all_in_one'); osc_delete_preference('allSeo_htaccess_enabled', 'plugin-all_in_one'); osc_delete_preference('allSeo_delimiter', 'plugin-all_in_one'); osc_delete_preference('allSeo_city_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_city_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_region_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_region_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_country_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_country_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_category_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_category_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_title_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_title_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_body_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_page_title', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_city_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_city_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_region_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_region_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_country_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_country_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_category_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_category_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_pattern_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_title_show', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_title_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_body_order', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_page_title', 'plugin-all_in_one'); osc_delete_preference('allSeo_search_improve_desc', 'plugin-all_in_one'); osc_delete_preference('allSeo_other_page_title', 'plugin-all_in_one'); osc_delete_preference('allSeo_sitemap_freq', 'plugin-all_in_one'); osc_delete_preference('allSeo_links_footer', 'plugin-all_in_one'); osc_delete_preference('allSeo_sitemap_items', 'plugin-all_in_one'); osc_delete_preference('allSeo_sitemap_items_limit', 'plugin-all_in_one'); osc_delete_preference('allSeo_allow_custom_meta', 'plugin-all_in_one'); //get list of primary keys of static pages (emails) that should be deleted on uninstall $pages = ModelSeoLink::newInstance()->getPages(); foreach ($pages as $page) { Page::newInstance()->deleteByPrimaryKey($page['pk_i_id']); } }
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); } } } } }
function fn_email_new_email($new_email, $validation_url) { $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)) { $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'), '<a href="' . osc_base_url() . '" >' . osc_base_url() . '</a>', osc_page_title(), '<a href="' . $validation_url . '" >' . $validation_url . '</a>', $validation_url); $title = osc_mailBeauty(osc_apply_filter('email_title', osc_apply_filter('email_new_email_title', $content['s_title'])), $words); $body = osc_mailBeauty(osc_apply_filter('email_description', osc_apply_filter('email_new_email_description', $content['s_text'])), $words); $params = array('subject' => $title, 'to' => $new_email, 'to_name' => Session::newInstance()->_get('userName'), 'body' => $body, 'alt_body' => $body); osc_sendMail($params); osc_add_flash_ok_message(_m('We have sent you an e-mail. Follow the instructions to validate the changes')); } else { osc_add_flash_error_message(_m('We tried to sent you an e-mail, but it failed. Please, contact the administrator')); } }
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 'userajax': // This is the autocomplete AJAX $users = User::newInstance()->ajax(Params::getParam("term")); if (count($users) == 0) { echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results')))); } else { echo json_encode($users); } break; case 'date_format': echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date(Params::getParam('format'))))); 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_admin_' . $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 ItemsProcessingAjax(Params::getParamsAsArray("get")); break; case 'users': // Return items (use external file oc-admin/ajax/item_processing.php) require_once osc_admin_base_path() . 'ajax/users_processing.php'; $users_processing = new UsersProcessingAjax(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 MediaProcessingAjax(Params::getParamsAsArray("get")); break; case 'categories_order': // Save the order of the categories $aIds = Params::getParam('list'); $orderParent = 0; $orderSub = 0; $catParent = 0; $error = 0; $catManager = Category::newInstance(); $aRecountCat = array(); foreach ($aIds as $id => $parent) { if ($parent == 'root') { $res = $catManager->updateOrder($id, $orderParent); if (is_bool($res) && !$res) { $error = 1; } // find category $auxCategory = Category::newInstance()->findByPrimaryKey($id); // set parent category $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = NULL; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok $parentId = $auxCategory['fk_i_parent_id']; if ($parentId) { // update parent category stats array_push($aRecountCat, $id); array_push($aRecountCat, $parentId); } } } $orderParent++; } else { if ($parent != $catParent) { $catParent = $parent; $orderSub = 0; } $res = $catManager->updateOrder($id, $orderSub); if (is_bool($res) && !$res) { $error = 1; } // set parent category $auxCategory = Category::newInstance()->findByPrimaryKey($id); $auxCategoryP = Category::newInstance()->findByPrimaryKey($catParent); $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = $catParent; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok // update category parent $prevParentId = $auxCategory['fk_i_parent_id']; $parentId = $auxCategoryP['pk_i_id']; array_push($aRecountCat, $prevParentId); array_push($aRecountCat, $parentId); } } $orderSub++; } } // update category stats foreach ($aRecountCat as $rId) { osc_update_cat_stats_id($rId); } if ($error) { $result = array('error' => __("Some error ocurred")); } else { $result = array('ok' => __("Order saved")); } echo json_encode($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; $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")) { // remove categories from a field Field::newInstance()->cleanCategoriesFromField(Params::getParam("id")); // no error... continue updating fields if ($error == 0) { $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name"); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $res = 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"))); if (is_bool($res) && !$res) { $error = 1; } } // no error... continue inserting categories-field if ($error == 0) { $aCategories = Params::getParam("categories"); if (is_array($aCategories) && count($aCategories) > 0) { $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories); if (!$res) { $error = 1; } } } // error while updating? if ($error == 1) { $message = __("Error while updating."); } } else { $error = 1; $message = __("Sorry, you already have one field with that name"); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => $field['pk_i_id']); } echo json_encode($result); break; case 'delete_field': $id = Params::getParam("id"); $error = 0; $fieldManager = Field::newInstance(); $res = $fieldManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The custom field have been deleted'); } else { $error = 1; $message = __('Error while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($result); break; case 'add_field': $s_name = __('NEW custom field'); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $fieldManager = Field::newInstance(); $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array()); if ($result) { echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name)); } else { echo json_encode(array('error' => 1)); } break; case 'enable_category': $id = strip_tags(Params::getParam('id')); $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0; $error = 0; $result = array(); $aUpdated = array(); $mCategory = Category::newInstance(); $aCategory = $mCategory->findByPrimaryKey($id); if ($aCategory == false) { $result = array('error' => sprintf(__("It doesn't exist a category with this id: %d"), $id)); echo json_encode($result); break; } // root category if ($aCategory['fk_i_parent_id'] == '') { $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id)); $subCategories = $mCategory->findSubcategories($id); $aIds = array($id); $aUpdated[] = array('id' => $id); foreach ($subCategories as $subcategory) { $aIds[] = $subcategory['pk_i_id']; $aUpdated[] = array('id' => $subcategory['pk_i_id']); } Item::newInstance()->enableByCategory($enabled, $aIds); if ($enabled) { $result = array('ok' => __('The category and its subcategories have been enabled')); } else { $result = array('ok' => __('The category and its subcategories have been disabled')); } $result['affectedIds'] = $aUpdated; echo json_encode($result); break; } // subcategory $parentCategory = $mCategory->findRootCategory($id); if (!$parentCategory['b_enabled']) { $result = array('error' => __('Parent category is disabled, you can not enable that category')); echo json_encode($result); break; } $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); if ($enabled) { $result = array('ok' => __('The subcategory has been enabled')); } else { $result = array('ok' => __('The subcategory has been disabled')); } $result['affectedIds'] = array(array('id' => $id)); echo json_encode($result); break; case 'delete_category': $id = Params::getParam("id"); $error = 0; $categoryManager = Category::newInstance(); $res = $categoryManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The categories have been deleted'); } else { $error = 1; $message = __('Error while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($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; $has_one_title = 0; $postParams = Params::getParamsAsArray(); foreach ($postParams as $k => $v) { if (preg_match('|(.+?)#(.+)|', $k, $m)) { if ($m[2] == 's_name') { if ($v != "") { $has_one_title = 1; $aFieldsDescription[$m[1]][$m[2]] = $v; $s_text = $v; } else { $aFieldsDescription[$m[1]][$m[2]] = ' '; $error = 1; } } else { $aFieldsDescription[$m[1]][$m[2]] = $v; } } } $l = osc_language(); if ($error == 0 || $error == 1 && $has_one_title == 1) { $categoryManager = Category::newInstance(); $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id); if (is_bool($res)) { $error = 2; } } if ($error == 0) { $msg = __("Category updated correctly"); } else { if ($error == 1) { if ($has_one_title == 1) { $error = 4; $msg = __('Category updated correctly, but some titles were empty'); } else { $msg = __('Sorry, at least a title is needed'); } } else { if ($error == 2) { $msg = __('Error while updating'); } } } echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name'])); break; case 'custom': // Execute via AJAX custom file $ajaxFile = Params::getParam("ajaxfile"); if ($ajaxFile == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (stripos($ajaxFile, '../') !== false) { echo json_encode(array('error' => 'no valid ajaxFile')); break; } if (!file_exists(osc_plugins_path() . $ajaxFile)) { echo json_encode(array('error' => "ajaxFile doesn't exist")); break; } require_once osc_plugins_path() . $ajaxFile; break; case 'test_mail': $title = sprintf(__('Test email, %s'), 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"); 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') { $page = $mPages->findPrevPage($actual_order); } else { if ($order == 'down') { $page = $mPages->findNextPage($actual_order); } } if (isset($page['i_order'])) { $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id)); $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id'])); } // TO BE IMPROVED // json for datatables $prefLocale = osc_current_user_locale(); $this->_exportVariableToView('pages', $mPages->listAll(0)); $o_json = array(); while (osc_has_static_pages()) { $row = array(); $page = osc_static_page(); $content = array(); if (isset($page['locale'][$prefLocale]) && !empty($page['locale'][$prefLocale]['s_title'])) { $content = $page['locale'][$prefLocale]; } else { $content = current($page['locale']); } $options = array(); $options[] = '<a href="' . osc_static_page_url() . '">' . __('View page') . '</a>'; $options[] = '<a href="' . osc_admin_base_url(true) . '?page=pages&action=edit&id=' . osc_static_page_id() . '">' . __('Edit') . '</a>'; if (!$page['b_indelible']) { $options[] = '<a onclick="javascript:return confirm(\'' . osc_esc_js("This action can't be undone. Are you sure you want to continue?") . '\')" href="' . osc_admin_base_url(true) . '?page=pages&action=delete&id=' . osc_static_page_id() . '">' . __('Delete') . '</a>'; } $row[] = '<input type="checkbox" name="id[]"" value="' . osc_static_page_id() . '"" />'; $row[] = $page['s_internal_name'] . '<div id="datatables_quick_edit" style="display: none;">' . implode(' · ', $options) . '</div>'; $row[] = $content['s_title']; $row[] = osc_static_page_order() . ' <img id="up" onclick="order_up(' . osc_static_page_id() . ');" style="cursor:pointer; width:15px; height:15px;" src="' . osc_current_admin_theme_url('images/arrow_up.png') . '"/> <br/><img id="down" onclick="order_down(' . osc_static_page_id() . ');" style="cursor:pointer; width:15px; height:15px; margin-left: 10px;" src="' . osc_current_admin_theme_url('images/arrow_down.png') . '"/>'; $o_json[] = $row; } echo json_encode($o_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; $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 **** ***********************/ $data = osc_file_get_contents("http://osclass.org/latest_version.php"); $data = json_decode(substr($data, 1, strlen($data) - 3), true); $source_file = $data['url']; if ($source_file != '') { $tmp = explode("/", $source_file); $filename = end($tmp); $result = osc_downloadFile($source_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 /************************ *** 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 = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $error_queries = $comm->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 ($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; case 'location_stats': $workToDo = LocationsTmp::newInstance()->count(); if ($workToDo > 0) { // there are wotk to do $aLocations = LocationsTmp::newInstance()->getLocations(1000); foreach ($aLocations as $location) { $id = $location['id_location']; $type = $location['e_type']; $data = 0; // update locations stats switch ($type) { case 'COUNTRY': $numItems = CountryStats::newInstance()->calculateNumItems($id); $data = CountryStats::newInstance()->setNumItems($id, $numItems); unset($numItems); break; case 'REGION': $numItems = RegionStats::newInstance()->calculateNumItems($id); $data = RegionStats::newInstance()->setNumItems($id, $numItems); unset($numItems); break; case 'CITY': $numItems = CityStats::newInstance()->calculateNumItems($id); $data = CityStats::newInstance()->setNumItems($id, $numItems); unset($numItems); break; default: break; } if ($data >= 0) { LocationsTmp::newInstance()->delete(array('e_type' => $location['e_type'], 'id_location' => $location['id_location'])); } } $array['status'] = 'more'; $array['pending'] = $workToDo = LocationsTmp::newInstance()->count(); echo json_encode($array); } else { $array['status'] = 'done'; echo json_encode($array); } break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
/** * Remove data and tables related to the plugin. */ public function uninstall() { $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_premium())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_publish())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_wallet())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_prices())); $this->dao->query(sprintf('DROP TABLE %s', $this->getTable_log())); $page = Page::newInstance()->findByInternalName('email_payment'); Page::newInstance()->deleteByPrimaryKey($page['pk_i_id']); osc_delete_preference('version', 'payment'); osc_delete_preference('default_premium_cost', 'payment'); osc_delete_preference('allow_premium', 'payment'); osc_delete_preference('default_publish_cost', 'payment'); osc_delete_preference('pay_per_post', 'payment'); osc_delete_preference('premium_days', 'payment'); osc_delete_preference('currency', 'payment'); osc_delete_preference('pack_price_1', 'payment'); osc_delete_preference('pack_price_2', 'payment'); osc_delete_preference('pack_price_3', 'payment'); osc_delete_preference('paypal_api_username', 'payment'); osc_delete_preference('paypal_api_password', 'payment'); osc_delete_preference('paypal_api_signature', 'payment'); osc_delete_preference('paypal_email', 'payment'); osc_delete_preference('paypal_standard', 'payment'); osc_delete_preference('paypal_sandbox', 'payment'); osc_delete_preference('paypal_enabled', 'payment'); osc_delete_preference('blockchain_btc_address', 'payment'); osc_delete_preference('blockchain_enabled', 'payment'); osc_delete_preference('braintree_merchant_id'); osc_delete_preference('braintree_public_key'); osc_delete_preference('braintree_private_key'); osc_delete_preference('braintree_encryption_key'); osc_delete_preference('braintree_sandbox'); osc_delete_preference('braintree_enabled'); }
/** * Generate and updates mails. * @param String $template HTML template to serve as a base. * @param Array $data New datas for emails and footer to use * to generate and update emails in oc_t_pages. * @return int Number of locales updated. */ public function update($template, $id, $newDatas, $nEmail) { $m = new Mustache_Engine(); $activeLocales = Madhouse_Utils_Collections::getFieldsFromList(osc_get_locales(), "pk_c_code"); if ($nEmail["s_internal_name"] == "exemple_page") { mdh_error_log(array($nEmail)); } $i = 0; foreach ($nEmail["locales"] as $l) { // Find the correct footer content. $footer = Madhouse_Utils_Collections::findByField($newDatas["footer"]["locales"], "fk_c_locale_code", $l["fk_c_locale_code"]); if (in_array($l["fk_c_locale_code"], $activeLocales) && !Madhouse_EmailMagick_Utils::isLocaleEmpty($l)) { // Updates the description using DAO method. Page::newInstance()->updateDescription($id, $l["fk_c_locale_code"], $l["s_title"], $m->render($template, array("CONTENT" => $l["s_text"], "TITLE" => $l["s_title"], "EXCERPT" => $l["s_excerpt"], "FOOTER" => $footer["s_text"]))); $i++; } } return $i; }