function digitalgoods_install() { DGModel::newInstance()->import('digitalgoods/struct.sql'); @mkdir(osc_content_path() . 'uploads/digitalgoods/'); osc_set_preference('upload_path', osc_content_path() . 'uploads/digitalgoods/', 'digitalgoods', 'STRING'); osc_set_preference('max_files', '1', 'digitalgoods', 'INTEGER'); osc_set_preference('allowed_ext', 'zip,rar,tgz', 'digitalgoods', 'INTEGER'); }
function qrcode_install() { @mkdir(osc_content_path() . 'uploads/qrcode/'); $conn = getConnection(); osc_set_preference('upload_path', osc_content_path() . 'uploads/qrcode/', 'qrcode', 'STRING'); osc_set_preference('upload_url', osc_base_url() . 'oc-content/uploads/qrcode/', 'qrcode', 'STRING'); osc_set_preference('code_size', '2', 'qrcode', 'INTEGER'); $conn->commit(); }
function doModel() { switch ($this->action) { case 'contact_post': //contact_post $yourName = Params::getParam('yourName'); $yourEmail = Params::getParam('yourEmail'); $subject = Params::getParam('subject'); $message = Params::getParam('message'); if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) { if (!osc_check_recaptcha()) { osc_add_flash_error_message(_m('The Recaptcha code is wrong')); Session::newInstance()->_setForm("yourName", $yourName); Session::newInstance()->_setForm("yourEmail", $yourEmail); Session::newInstance()->_setForm("subject", $subject); Session::newInstance()->_setForm("message_body", $message); $this->redirectTo(osc_contact_url()); return false; // BREAK THE PROCESS, THE RECAPTCHA IS WRONG } } if (!preg_match('|.*?@.{2,}\\..{2,}|', $yourEmail)) { osc_add_flash_error_message(_m('Please enter a correct email')); Session::newInstance()->_setForm("yourName", $yourName); Session::newInstance()->_setForm("subject", $subject); Session::newInstance()->_setForm("message_body", $message); $this->redirectTo(osc_contact_url()); } $message = sprintf(__("%s (%s) left this message : %s"), $yourName, $yourEmail, $message); $params = array('reply_to' => $yourEmail, 'subject' => '[' . osc_page_title() . '] ' . __('Contact form') . ': ' . $subject, 'to' => osc_contact_email(), 'to_name' => __('Administrator'), 'body' => $message, 'alt_body' => $message); if (osc_contact_attachment()) { $attachment = Params::getFiles('attachment'); $resourceName = $attachment['name']; $tmpName = $attachment['tmp_name']; $resourceType = $attachment['type']; $path = osc_content_path() . 'uploads/' . time() . '_' . $resourceName; if (!is_writable(osc_content_path() . 'uploads/')) { osc_add_flash_error_message(_m('There have been some errors sending the message')); $this->redirectTo(osc_contact_url()); } if (!move_uploaded_file($tmpName, $path)) { unset($path); } } if (isset($path)) { $params['attachment'] = $path; } osc_sendMail($params); osc_add_flash_ok_message(_m('Your email has been sent properly. Thank you for contacting us!')); $this->redirectTo(osc_contact_url()); break; default: //contact $this->doView('contact.php'); } }
function doModel() { switch ($this->action) { case 'media': // calling the media view $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $memory_limit = (int) ini_get('memory_limit'); $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024; $this->_exportVariableToView('max_size_upload', $upload_mb); $this->doView('settings/media.php'); break; case 'media_post': // updating the media config osc_csrf_check(); $status = 'ok'; $error = ''; $iUpdated = 0; $maxSizeKb = Params::getParam('maxSizeKb'); $dimThumbnail = strtolower(Params::getParam('dimThumbnail')); $dimPreview = strtolower(Params::getParam('dimPreview')); $dimNormal = strtolower(Params::getParam('dimNormal')); $keepOriginalImage = Params::getParam('keep_original_image'); $forceAspectImage = Params::getParam('force_aspect_image'); $forceJPEG = Params::getParam('force_jpeg'); $use_imagick = Params::getParam('use_imagick'); $type_watermark = Params::getParam('watermark_type'); $watermark_color = Params::getParam('watermark_text_color'); $watermark_text = Params::getParam('watermark_text'); switch ($type_watermark) { case 'none': $iUpdated += osc_set_preference('watermark_text_color', ''); $iUpdated += osc_set_preference('watermark_text', ''); $iUpdated += osc_set_preference('watermark_image', ''); break; case 'text': $iUpdated += osc_set_preference('watermark_text_color', $watermark_color); $iUpdated += osc_set_preference('watermark_text', $watermark_text); $iUpdated += osc_set_preference('watermark_image', ''); $iUpdated += osc_set_preference('watermark_place', Params::getParam('watermark_text_place')); break; case 'image': // upload image & move to path $watermark_file = Params::getFiles('watermark_image'); if ($watermark_file['tmp_name'] != '' && $watermark_file['size'] > 0) { if ($watermark_file['error'] == UPLOAD_ERR_OK) { if ($watermark_file['type'] == 'image/png') { $tmpName = $watermark_file['tmp_name']; $path = osc_content_path() . 'uploads/watermark.png'; if (move_uploaded_file($tmpName, $path)) { $iUpdated += osc_set_preference('watermark_image', $path); } else { $status = 'error'; $error .= _m('There was a problem uploading the watermark image') . "<br />"; } } else { $status = 'error'; $error .= _m('The watermark image has to be a .PNG file') . "<br />"; } } else { $status = 'error'; $error .= _m('There was a problem uploading the watermark image') . "<br />"; } } $iUpdated += osc_set_preference('watermark_text_color', ''); $iUpdated += osc_set_preference('watermark_text', ''); $iUpdated += osc_set_preference('watermark_place', Params::getParam('watermark_image_place')); break; default: break; } // format parameters $maxSizeKb = trim(strip_tags($maxSizeKb)); $dimThumbnail = trim(strip_tags($dimThumbnail)); $dimPreview = trim(strip_tags($dimPreview)); $dimNormal = trim(strip_tags($dimNormal)); $keepOriginalImage = $keepOriginalImage != '' ? true : false; $forceAspectImage = $forceAspectImage != '' ? true : false; $forceJPEG = $forceJPEG != '' ? true : false; $use_imagick = $use_imagick != '' ? true : false; if (!preg_match('|([0-9]+)x([0-9]+)|', $dimThumbnail, $match)) { $dimThumbnail = is_numeric($dimThumbnail) ? $dimThumbnail . "x" . $dimThumbnail : "100x100"; } if (!preg_match('|([0-9]+)x([0-9]+)|', $dimPreview, $match)) { $dimPreview = is_numeric($dimPreview) ? $dimPreview . "x" . $dimPreview : "100x100"; } if (!preg_match('|([0-9]+)x([0-9]+)|', $dimNormal, $match)) { $dimNormal = is_numeric($dimNormal) ? $dimNormal . "x" . $dimNormal : "100x100"; } // is imagick extension loaded? if (!@extension_loaded('imagick')) { $use_imagick = false; } // max size allowed by PHP configuration? $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $memory_limit = (int) ini_get('memory_limit'); $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024; // set maxSizeKB equals to PHP configuration if it's bigger if ($maxSizeKb > $upload_mb) { $status = 'warning'; $maxSizeKb = $upload_mb; // flash message text warning $error .= sprintf(_m("You cannot set a maximum file size higher than the one allowed in the PHP configuration: <b>%d KB</b>"), $upload_mb); } $iUpdated += osc_set_preference('maxSizeKb', $maxSizeKb); $iUpdated += osc_set_preference('dimThumbnail', $dimThumbnail); $iUpdated += osc_set_preference('dimPreview', $dimPreview); $iUpdated += osc_set_preference('dimNormal', $dimNormal); $iUpdated += osc_set_preference('keep_original_image', $keepOriginalImage); $iUpdated += osc_set_preference('force_aspect_image', $forceAspectImage); $iUpdated += osc_set_preference('force_jpeg', $forceJPEG); $iUpdated += osc_set_preference('use_imagick', $use_imagick); if ($error != '') { switch ($status) { case 'error': osc_add_flash_error_message($error, 'admin'); break; case 'warning': osc_add_flash_warning_message($error, 'admin'); break; default: osc_add_flash_ok_message($error, 'admin'); break; } } else { osc_add_flash_ok_message(_m('Media config has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); break; case 'images_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); } osc_csrf_check(); $aResources = ItemResource::newInstance()->getAllResources(); foreach ($aResources as $resource) { osc_run_hook('regenerate_image', $resource); if (strpos($resource['s_content_type'], 'image') !== false) { if (file_exists(osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_original." . $resource['s_extension'])) { $image_tmp = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_original." . $resource['s_extension']; $use_original = true; } else { if (file_exists(osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "." . $resource['s_extension'])) { $image_tmp = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "." . $resource['s_extension']; $use_original = false; } else { if (file_exists(osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_preview." . $resource['s_extension'])) { $image_tmp = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_preview." . $resource['s_extension']; $use_original = false; } else { $use_original = false; continue; } } } // Create normal size $path_normal = $path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '.' . $resource['s_extension']; $size = explode('x', osc_normal_dimensions()); $img = ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1]); if ($use_original) { if (osc_is_watermark_text()) { $img->doWatermarkText(osc_watermark_text(), osc_watermark_text_color()); } elseif (osc_is_watermark_image()) { $img->doWatermarkImage(); } } $img->saveToFile($path); // Create preview $path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '_preview.' . $resource['s_extension']; $size = explode('x', osc_preview_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // Create thumbnail $path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '_thumbnail.' . $resource['s_extension']; $size = explode('x', osc_thumbnail_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id'])); } else { // no es imagen o imagen sin extesión } } osc_add_flash_ok_message(_m('Re-generation complete'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); break; } }
function doModel() { parent::doModel(); //specific things for this class switch ($this->action) { case 'add': $this->doView("appearance/add.php"); break; case 'add_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=appearance'); } osc_csrf_check(); $filePackage = Params::getFiles('package'); if (isset($filePackage['size']) && $filePackage['size'] != 0) { $path = osc_themes_path(); (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path)); @unlink($filePackage['tmp_name']); } else { $status = 3; } switch ($status) { case 0: $msg = _m('The theme folder is not writable'); osc_add_flash_error_message($msg, 'admin'); break; case 1: $msg = _m('The theme has been installed correctly'); osc_add_flash_ok_message($msg, 'admin'); break; case 2: $msg = _m('The zip file is not valid'); osc_add_flash_error_message($msg, 'admin'); break; case 3: $msg = _m('No file was uploaded'); osc_add_flash_error_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=add"); break; case -1: default: $msg = _m('There was a problem adding the theme'); osc_add_flash_error_message($msg, 'admin'); break; } $this->redirectTo(osc_admin_base_url(true) . "?page=appearance"); break; case 'delete': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=appearance'); } osc_csrf_check(); $theme = Params::getParam('webtheme'); if ($theme != '') { if ($theme != osc_current_web_theme()) { if (file_exists(osc_content_path() . "themes/" . $theme . "/functions.php")) { include osc_content_path() . "themes/" . $theme . "/functions.php"; } osc_run_hook("theme_delete_" . $theme); if (osc_deleteDir(osc_content_path() . "themes/" . $theme . "/")) { osc_add_flash_ok_message(_m("Theme removed successfully"), "admin"); } else { osc_add_flash_error_message(_m("There was a problem removing the theme"), "admin"); } } else { osc_add_flash_error_message(_m("Current theme can not be deleted"), "admin"); } } else { osc_add_flash_error_message(_m("No theme selected"), "admin"); } $this->redirectTo(osc_admin_base_url(true) . "?page=appearance"); break; /* widgets */ /* widgets */ case 'widgets': $info = WebThemes::newInstance()->loadThemeInfo(osc_theme()); $this->_exportVariableToView("info", $info); $this->doView('appearance/widgets.php'); break; case 'add_widget': $this->doView('appearance/add_widget.php'); break; case 'edit_widget': $id = Params::getParam('id'); $widget = Widget::newInstance()->findByPrimaryKey($id); $this->_exportVariableToView("widget", $widget); $this->doView('appearance/add_widget.php'); break; case 'delete_widget': osc_csrf_check(); Widget::newInstance()->delete(array('pk_i_id' => Params::getParam('id'))); osc_add_flash_ok_message(_m('Widget removed correctly'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); break; case 'edit_widget_post': osc_csrf_check(); if (!osc_validate_text(Params::getParam("description"))) { osc_add_flash_error_message(_m('Description field is required'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); } $res = Widget::newInstance()->update(array('s_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)), array('pk_i_id' => Params::getParam('id'))); if ($res) { osc_add_flash_ok_message(_m('Widget updated correctly'), 'admin'); } else { osc_add_flash_error_message(_m('Widget cannot be updated correctly'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); break; case 'add_widget_post': osc_csrf_check(); if (!osc_validate_text(Params::getParam("description"))) { osc_add_flash_error_message(_m('Description field is required'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); } Widget::newInstance()->insert(array('s_location' => Params::getParam('location'), 'e_kind' => 'html', 's_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false))); osc_add_flash_ok_message(_m('Widget added correctly'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); break; /* /widget */ /* /widget */ case 'activate': osc_csrf_check(); osc_set_preference('theme', Params::getParam('theme')); osc_add_flash_ok_message(_m('Theme activated correctly'), 'admin'); osc_run_hook("theme_activate", Params::getParam('theme')); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance"); break; case 'render': if (Params::existParam('route')) { $routes = Rewrite::newInstance()->getRoutes(); $rid = Params::getParam('route'); $file = '../'; if (isset($routes[$rid]) && isset($routes[$rid]['file'])) { $file = $routes[$rid]['file']; } } else { // DEPRECATED: Disclosed path in URL is deprecated, use routes instead // This will be REMOVED in 3.6 $file = Params::getParam('file'); // We pass the GET variables (in case we have somes) if (preg_match('|(.+?)\\?(.*)|', $file, $match)) { $file = $match[1]; if (preg_match_all('|&([^=]+)=([^&]*)|', urldecode('&' . $match[2] . '&'), $get_vars)) { for ($var_k = 0; $var_k < count($get_vars[1]); $var_k++) { Params::setParam($get_vars[1][$var_k], $get_vars[2][$var_k]); } } } else { $file = Params::getParam('file'); } } if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || !file_exists(osc_base_path() . $file)) { osc_add_flash_warning_message(__('Error loading theme custom file'), 'admin'); } $this->_exportVariableToView('file', osc_base_path() . $file); $this->doView('appearance/view.php'); break; default: if (Params::getParam('checkUpdated') != '') { osc_admin_toolbar_update_themes(true); } $themes = WebThemes::newInstance()->getListThemes(); //preparing variables for the view $this->_exportVariableToView("themes", $themes); $this->doView('appearance/index.php'); break; } }
public function uploadItemResources($aResources, $itemId) { if ($aResources != '') { $wat = new Watermark(); $itemResourceManager = ItemResource::newInstance(); $numImagesItems = osc_max_images_per_item(); $numImages = $itemResourceManager->countResources($itemId); foreach ($aResources['error'] as $key => $error) { if ($numImagesItems == 0 || $numImagesItems > 0 && $numImages < $numImagesItems) { if ($error == UPLOAD_ERR_OK) { $numImages++; $tmpName = $aResources['tmp_name'][$key]; $itemResourceManager->insert(array('fk_i_item_id' => $itemId)); $resourceId = $itemResourceManager->dao->insertedId(); // Create normal size $normal_path = $path = osc_content_path() . 'uploads/' . $resourceId . '.jpg'; $size = explode('x', osc_normal_dimensions()); ImageResizer::fromFile($tmpName)->resizeTo($size[0], $size[1])->saveToFile($path); if (osc_is_watermark_text()) { $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg'); } elseif (osc_is_watermark_image()) { $wat->doWatermarkImage($path, 'image/jpeg'); } // Create preview $path = osc_content_path() . 'uploads/' . $resourceId . '_preview.jpg'; $size = explode('x', osc_preview_dimensions()); ImageResizer::fromFile($normal_path)->resizeTo($size[0], $size[1])->saveToFile($path); // Create thumbnail $path = osc_content_path() . 'uploads/' . $resourceId . '_thumbnail.jpg'; $size = explode('x', osc_thumbnail_dimensions()); ImageResizer::fromFile($normal_path)->resizeTo($size[0], $size[1])->saveToFile($path); if (osc_keep_original_image()) { $path = osc_content_path() . 'uploads/' . $resourceId . '_original.jpg'; move_uploaded_file($tmpName, $path); } $s_path = 'oc-content/uploads/'; $resourceType = 'image/jpeg'; $itemResourceManager->update(array('s_path' => $s_path, 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => $resourceType), array('pk_i_id' => $resourceId, 'fk_i_item_id' => $itemId)); osc_run_hook('uploaded_file', ItemResource::newInstance()->findByPrimaryKey($resourceId)); } } } unset($itemResourceManager); } }
function doModel() { switch ($this->action) { case 'comments': //calling the comments settings view $this->doView('settings/comments.php'); break; case 'comments_post': // updating comment $iUpdated = 0; $enabledComments = Params::getParam('enabled_comments'); $enabledComments = $enabledComments != '' ? true : false; $moderateComments = Params::getParam('moderate_comments'); $moderateComments = $moderateComments != '' ? true : false; $numModerateComments = Params::getParam('num_moderate_comments'); $commentsPerPage = Params::getParam('comments_per_page'); $notifyNewComment = Params::getParam('notify_new_comment'); $notifyNewComment = $notifyNewComment != '' ? true : false; $regUserPostComments = Params::getParam('reg_user_post_comments'); $regUserPostComments = $regUserPostComments != '' ? true : false; $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledComments), array('s_name' => 'enabled_comments')); if ($moderateComments) { $iUpdated += Preference::newInstance()->update(array('s_value' => $numModerateComments), array('s_name' => 'moderate_comments')); } else { $iUpdated += Preference::newInstance()->update(array('s_value' => '-1'), array('s_name' => 'moderate_comments')); } $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewComment), array('s_name' => 'notify_new_comment')); $iUpdated += Preference::newInstance()->update(array('s_value' => $commentsPerPage), array('s_name' => 'comments_per_page')); $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserPostComments), array('s_name' => 'reg_user_post_comments')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Comments\' settings have been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments'); break; case 'locations': // calling the locations settings view $location_action = Params::getParam('type'); $mCountries = new Country(); switch ($location_action) { case 'add_country': // add country $countryCode = strtoupper(Params::getParam('c_country')); $request = Params::getParam('country'); foreach ($request as $k => $v) { $countryName = $v; break; } $exists = $mCountries->findByCode($countryCode); if (isset($exists['s_name'])) { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $countryName), 'admin'); } else { $countries_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=country_code&term=' . urlencode($countryCode)); $countries = json_decode($countries_json); foreach ($request as $k => $v) { $data = array('pk_c_code' => $countryCode, 'fk_c_locale_code' => $k, 's_name' => $v); $mCountries->insert($data); } if (isset($countries->error)) { // Country is not in our GEO database // We have no region for user-typed countries } else { // Country is in our GEO database, add regions and cities $manager_region = new Region(); $regions_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=region&country_code=' . urlencode($countryCode) . '&term=all'); $regions = json_decode($regions_json); if (!isset($regions->error)) { if (count($regions) > 0) { foreach ($regions as $r) { $manager_region->insert(array("fk_c_country_code" => $r->country_code, "s_name" => $r->name)); } } unset($regions); unset($regions_json); $manager_city = new City(); if (count($countries) > 0) { foreach ($countries as $c) { $regions = $manager_region->listWhere('fk_c_country_code = \'' . $c->id . '\''); if (!isset($regions->error)) { if (count($regions) > 0) { foreach ($regions as $region) { $cities_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=city&country=' . urlencode($c->name) . '®ion=' . urlencode($region['s_name']) . '&term=all'); $cities = json_decode($cities_json); if (!isset($cities->error)) { if (count($cities) > 0) { foreach ($cities as $ci) { $manager_city->insert(array("fk_i_region_id" => $region['pk_i_id'], "s_name" => $ci->name, "fk_c_country_code" => $ci->country_code)); } } } unset($cities); unset($cities_json); } } } } } } } osc_add_flash_ok_message(sprintf(_m('%s has been added as a new country'), $countryName), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'edit_country': // edit country $countryCode = Params::getParam('country_code'); $request = Params::getParam('e_country'); $ok = true; foreach ($request as $k => $v) { $result = $mCountries->updateLocale($countryCode, $k, $v); if (!$result) { $ok = false; } } if ($ok) { osc_add_flash_ok_message(_m('Country has been edited'), 'admin'); } else { osc_add_flash_ok_message(_m('There were some problems editing the country'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'delete_country': // delete country $countryId = Params::getParam('id'); // HAS ITEMS? $has_items = Item::newInstance()->listWhere('l.fk_c_country_code = \'%s\' LIMIT 1', $countryId); if (!$has_items) { $mRegions = new Region(); $mCities = new City(); $aCountries = $mCountries->findByCode($countryId); $aRegions = $mRegions->listWhere('fk_c_country_code = \'' . $aCountries['pk_c_code'] . '\''); foreach ($aRegions as $region) { $mCities->delete(array('fk_i_region_id' => $region['pk_i_id'])); $mRegions->delete(array('pk_i_id' => $region['pk_i_id'])); } $mCountries->delete(array('pk_c_code' => $aCountries['pk_c_code'])); osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aCountries['s_name']), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s can not be deleted, some items are located in it'), $aCountries['s_name']), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'add_region': // add region if (!Params::getParam('r_manual')) { $this->install_location_by_region(); } else { $mRegions = new Region(); $regionName = Params::getParam('region'); $countryCode = Params::getParam('country_c_parent'); $exists = $mRegions->findByNameAndCode($regionName, $countryCode); if (!isset($exists['s_name'])) { $data = array('fk_c_country_code' => $countryCode, 's_name' => $regionName); $mRegions->insert($data); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new region'), $regionName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $regionName), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'edit_region': // edit region $mRegions = new Region(); $newRegion = Params::getParam('e_region'); $regionId = Params::getParam('region_id'); $exists = $mRegions->findByName($newRegion); if (!$exists['pk_i_id'] || $exists['pk_i_id'] == $regionId) { if ($regionId != '') { $mRegions->update(array('s_name' => $newRegion), array('pk_i_id' => $regionId)); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newRegion), 'admin'); } } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newRegion), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'delete_region': // delete region $mRegion = new Region(); $mCities = new City(); $regionId = Params::getParam('id'); if ($regionId != '') { $aRegion = $mRegion->findByPrimaryKey($regionId); $mCities->delete(array('fk_i_region_id' => $regionId)); $mRegion->delete(array('pk_i_id' => $regionId)); osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aRegion['s_name']), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'add_city': // add city $mCities = new City(); $regionId = Params::getParam('region_parent'); $countryCode = Params::getParam('country_c_parent'); $newCity = Params::getParam('city'); $exists = $mCities->findByNameAndRegion($newCity, $regionId); if (!isset($exists['s_name'])) { $mCities->insert(array('fk_i_region_id' => $regionId, 's_name' => $newCity, 'fk_c_country_code' => $countryCode)); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new city'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'edit_city': // edit city $mCities = new City(); $newCity = Params::getParam('e_city'); $cityId = Params::getParam('city_id'); $exists = $mCities->findByName($newCity); if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $cityId) { $mCities->update(array('s_name' => $newCity), array('pk_i_id' => $cityId)); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'delete_city': // delete city $mCities = new City(); $cityId = Params::getParam('id'); $aCity = $mCities->findByPrimaryKey($cityId); $mCities->delete(array('pk_i_id' => $cityId)); osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aCity['s_name']), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; } $aCountries = $mCountries->listAllAdmin(); $this->_exportVariableToView('aCountries', $aCountries); $this->doView('settings/locations.php'); break; case 'permalinks': // calling the permalinks view $htaccess = Params::getParam('htaccess_status'); $file = Params::getParam('file_status'); $this->_exportVariableToView('htaccess', $htaccess); $this->_exportVariableToView('file', $file); $this->doView('settings/permalinks.php'); break; case 'permalinks_post': // updating permalinks option $htaccess_status = 0; $file_status = 0; $rewriteEnabled = Params::getParam('rewrite_enabled'); $rewriteEnabled = $rewriteEnabled ? true : false; if ($rewriteEnabled) { Preference::newInstance()->update(array('s_value' => '1'), array('s_name' => 'rewriteEnabled')); require_once ABS_PATH . 'generate_rules.php'; $htaccess = ' <IfModule mod_rewrite.c> RewriteEngine On RewriteBase ' . REL_WEB_URL . ' RewriteRule ^index\\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . ' . REL_WEB_URL . 'index.php [L] </IfModule>'; if (file_exists(osc_base_path() . '.htaccess')) { $file_status = 1; } else { if (file_put_contents(osc_base_path() . '.htaccess', $htaccess)) { $file_status = 2; } else { $file_status = 3; } } if (apache_mod_loaded('mod_rewrite')) { $htaccess_status = 1; Preference::newInstance()->update(array('s_value' => '1'), array('s_name' => 'mod_rewrite_loaded')); } else { $htaccess_status = 2; Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'mod_rewrite_loaded')); } } else { $modRewrite = apache_mod_loaded('mod_rewrite'); Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'rewriteEnabled')); Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'mod_rewrite_loaded')); } $redirectUrl = osc_admin_base_url(true) . '?page=settings&action=permalinks&htaccess_status='; $redirectUrl .= $htaccess_status . '&file_status=' . $file_status; $this->redirectTo($redirectUrl); break; case 'spamNbots': // calling the spam and bots view $this->doView('settings/spamNbots.php'); break; case 'spamNbots_post': // updating spam and bots option $iUpdated = 0; $akismetKey = Params::getParam('akismetKey'); $akismetKey = trim($akismetKey); $recaptchaPrivKey = Params::getParam('recaptchaPrivKey'); $recaptchaPrivKey = trim($recaptchaPrivKey); $recaptchaPubKey = Params::getParam('recaptchaPubKey'); $recaptchaPubKey = trim($recaptchaPubKey); $iUpdated += Preference::newInstance()->update(array('s_value' => $akismetKey), array('s_name' => 'akismetKey')); $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPrivKey), array('s_name' => 'recaptchaPrivKey')); $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPubKey), array('s_name' => 'recaptchaPubKey')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Akismet and reCAPTCHA have been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=spamNbots'); break; case 'currencies': // currencies settings $currencies_action = Params::getParam('type'); switch ($currencies_action) { case 'add': // calling add currency view $this->doView('settings/add_currency.php'); break; case 'add_post': // adding a new currency $currencyCode = Params::getParam('pk_c_code'); $currencyName = Params::getParam('s_name'); $currencyDescription = Params::getParam('s_description'); // cleaning parameters $currencyName = strip_tags($currencyName); $currencyDescription = strip_tags($currencyDescription); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if (!preg_match('/^.{1,3}$/', $currencyCode)) { osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $fields = array('pk_c_code' => $currencyCode, 's_name' => $currencyName, 's_description' => $currencyDescription); $isInserted = Currency::newInstance()->insert($fields); if ($isInserted) { osc_add_flash_ok_message(_m('New currency has been added'), 'admin'); } else { osc_add_flash_error_message(_m('Error: currency couldn\'t be added'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; case 'edit': // calling edit currency view $currencyCode = Params::getParam('code'); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if ($currencyCode == '') { osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $aCurrency = Currency::newInstance()->findByCode($currencyCode); if (count($aCurrency) == 0) { osc_add_flash_error_message(_m('Error: the currency doesn\'t exist'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $this->_exportVariableToView('aCurrency', $aCurrency); $this->doView('settings/edit_currency.php'); break; case 'edit_post': // updating currency $currencyName = Params::getParam('s_name'); $currencyDescription = Params::getParam('s_description'); $currencyCode = Params::getParam('pk_c_code'); // cleaning parameters $currencyName = strip_tags($currencyName); $currencyDescription = strip_tags($currencyDescription); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if (!preg_match('/.{1,3}/', $currencyCode)) { osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $iUpdated = Currency::newInstance()->update(array('s_name' => $currencyName, 's_description' => $currencyDescription), array('pk_c_code' => $currencyCode)); if ($iUpdated == 1) { osc_add_flash_ok_message(_m('Currency has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; case 'delete': // deleting a currency $rowChanged = 0; $aCurrencyCode = Params::getParam('code'); if (!is_array($aCurrencyCode)) { osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $msg_current = ''; foreach ($aCurrencyCode as $currencyCode) { if (preg_match('/.{1,3}/', $currencyCode) && $currencyCode != osc_currency()) { $rowChanged += Currency::newInstance()->delete(array('pk_c_code' => $currencyCode)); } if ($currencyCode == osc_currency()) { $msg_current = sprintf('. ' . _m("%s could not be deleted because it's the default currency"), $currencyCode); } } $msg = ''; switch ($rowChanged) { case '0': $msg = _m('No currencies have been deleted'); osc_add_flash_error_message($msg . $msg_current, 'admin'); break; case '1': $msg = _m('One currency has been deleted'); osc_add_flash_ok_message($msg . $msg_current, 'admin'); break; case '-1': $msg = sprintf(_m("%s could not be deleted because this currency still in use"), $currencyCode); osc_add_flash_error_message($msg . $msg_current, 'admin'); break; default: $msg = sprintf(_m('%s currencies have been deleted'), $rowChanged); osc_add_flash_ok_message($msg . $msg_current, 'admin'); break; } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; default: // calling the currencies view $aCurrencies = Currency::newInstance()->listAll(); $this->_exportVariableToView('aCurrencies', $aCurrencies); $this->doView('settings/currencies.php'); break; } break; case 'mailserver': // calling the mailserver view $this->doView('settings/mailserver.php'); break; case 'mailserver_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); } // updating mailserver $iUpdated = 0; $mailserverAuth = Params::getParam('mailserver_auth'); $mailserverAuth = $mailserverAuth != '' ? true : false; $mailserverPop = Params::getParam('mailserver_pop'); $mailserverPop = $mailserverPop != '' ? true : false; $mailserverType = Params::getParam('mailserver_type'); $mailserverHost = Params::getParam('mailserver_host'); $mailserverPort = Params::getParam('mailserver_port'); $mailserverUsername = Params::getParam('mailserver_username'); $mailserverPassword = Params::getParam('mailserver_password'); $mailserverSsl = Params::getParam('mailserver_ssl'); if (!in_array($mailserverType, array('custom', 'gmail'))) { osc_add_flash_error_message(_m('Mail server type is incorrect'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverAuth), array('s_name' => 'mailserver_auth')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPop), array('s_name' => 'mailserver_pop')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverType), array('s_name' => 'mailserver_type')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverHost), array('s_name' => 'mailserver_host')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPort), array('s_name' => 'mailserver_port')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverUsername), array('s_name' => 'mailserver_username')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPassword), array('s_name' => 'mailserver_password')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverSsl), array('s_name' => 'mailserver_ssl')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Mail server configuration has changed'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); break; case 'media': // calling the media view $this->doView('settings/media.php'); break; case 'media_post': // updating the media config $iUpdated = 0; $maxSizeKb = Params::getParam('maxSizeKb'); $allowedExt = Params::getParam('allowedExt'); $dimThumbnail = Params::getParam('dimThumbnail'); $dimPreview = Params::getParam('dimPreview'); $dimNormal = Params::getParam('dimNormal'); $keepOriginalImage = Params::getParam('keep_original_image'); $use_imagick = Params::getParam('use_imagick'); $type_watermark = Params::getParam('watermark_type'); $watermark_color = Params::getParam('watermark_text_color'); $watermark_text = Params::getParam('watermark_text'); $watermark_image = Params::getParam('watermark_image'); switch ($type_watermark) { case 'none': $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image')); break; case 'text': $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_color), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_text), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image')); $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_text_place')), array('s_name' => 'watermark_place')); break; case 'image': // upload image & move to path if ($_FILES['watermark_image']['error'] == UPLOAD_ERR_OK) { $tmpName = $_FILES['watermark_image']['tmp_name']; $path = osc_content_path() . 'uploads/watermark.png'; if (move_uploaded_file($tmpName, $path)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $path), array('s_name' => 'watermark_image')); } else { $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image')); } } $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_image_place')), array('s_name' => 'watermark_place')); break; default: break; } // format parameters $maxSizeKb = strip_tags($maxSizeKb); $allowedExt = strip_tags($allowedExt); $dimThumbnail = strip_tags($dimThumbnail); $dimPreview = strip_tags($dimPreview); $dimNormal = strip_tags($dimNormal); $keepOriginalImage = $keepOriginalImage != '' ? true : false; $use_imagick = $use_imagick != '' ? true : false; if (!extension_loaded('imagick')) { $use_imagick = false; } $iUpdated += Preference::newInstance()->update(array('s_value' => $maxSizeKb), array('s_name' => 'maxSizeKb')); $iUpdated += Preference::newInstance()->update(array('s_value' => $allowedExt), array('s_name' => 'allowedExt')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimThumbnail), array('s_name' => 'dimThumbnail')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimPreview), array('s_name' => 'dimPreview')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimNormal), array('s_name' => 'dimNormal')); $iUpdated += Preference::newInstance()->update(array('s_value' => $keepOriginalImage), array('s_name' => 'keep_original_image')); $iUpdated += Preference::newInstance()->update(array('s_value' => $use_imagick), array('s_name' => 'use_imagick')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Media config has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); break; case 'contact': // calling the media view $this->doView('settings/contact.php'); break; case 'contact_post': // updating the media config $enabled_attachment = Params::getParam('enabled_attachment'); if ($enabled_attachment == '') { $enabled_attachment = 0; } else { $enabled_attachment = 1; } // format parameters $iUpdated = Preference::newInstance()->update(array('s_value' => $enabled_attachment), array('s_name' => 'contact_attachment')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Contact configuration has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=contact'); break; case 'cron': // viewing the cron view $this->doView('settings/cron.php'); break; case 'cron_post': // updating cron config $iUpdated = 0; $bAutoCron = Params::getParam('auto_cron'); $bAutoCron = $bAutoCron != '' ? true : false; $iUpdated += Preference::newInstance()->update(array('s_value' => $bAutoCron), array('s_name' => 'auto_cron')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Cron config has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=cron'); break; case 'update': // update index view $iUpdated = 0; $sPageTitle = Params::getParam('pageTitle'); $sPageDesc = Params::getParam('pageDesc'); $sContactEmail = Params::getParam('contactEmail'); $sLanguage = Params::getParam('language'); $sDateFormat = Params::getParam('dateFormat'); $sCurrency = Params::getParam('currency'); $sWeekStart = Params::getParam('weekStart'); $sTimeFormat = Params::getParam('timeFormat'); $sTimezone = Params::getParam('timezone'); $sNumRssItems = Params::getParam('num_rss_items'); $maxLatestItems = Params::getParam('max_latest_items_at_home'); // preparing parameters $sPageTitle = strip_tags($sPageTitle); $sPageDesc = strip_tags($sPageDesc); $sContactEmail = strip_tags($sContactEmail); $sLanguage = strip_tags($sLanguage); $sDateFormat = strip_tags($sDateFormat); $sCurrency = strip_tags($sCurrency); $sWeekStart = strip_tags($sWeekStart); $sTimeFormat = strip_tags($sTimeFormat); $sNumRssItems = (int) strip_tags($sNumRssItems); $maxLatestItems = (int) strip_tags($maxLatestItems); $error = ""; $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageTitle), array('s_section' => 'osclass', 's_name' => 'pageTitle')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageDesc), array('s_section' => 'osclass', 's_name' => 'pageDesc')); if (!defined('DEMO')) { $iUpdated += Preference::newInstance()->update(array('s_value' => $sContactEmail), array('s_section' => 'osclass', 's_name' => 'contactEmail')); } $iUpdated += Preference::newInstance()->update(array('s_value' => $sLanguage), array('s_section' => 'osclass', 's_name' => 'language')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sDateFormat), array('s_section' => 'osclass', 's_name' => 'dateFormat')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sCurrency), array('s_section' => 'osclass', 's_name' => 'currency')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sWeekStart), array('s_section' => 'osclass', 's_name' => 'weekStart')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimeFormat), array('s_section' => 'osclass', 's_name' => 'timeFormat')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimezone), array('s_section' => 'osclass', 's_name' => 'timezone')); if (is_int($sNumRssItems)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $sNumRssItems), array('s_section' => 'osclass', 's_name' => 'num_rss_items')); } else { if ($error != '') { $error .= "<br/>"; } $error .= _m('Number of items in the RSS must be integer'); } if (is_int($maxLatestItems)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $maxLatestItems), array('s_section' => 'osclass', 's_name' => 'maxLatestItems@home')); } else { if ($error != '') { $error .= "<br/>"; } $error .= _m('Number of recent items displayed at home must be integer'); } if ($iUpdated > 0) { if ($error != '') { osc_add_flash_error_message($error . "<br/>" . _m('General settings have been updated'), 'admin'); } else { osc_add_flash_ok_message(_m('General settings have been updated'), 'admin'); } } else { if ($error != '') { osc_add_flash_error_message($error, 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings'); break; case 'latestsearches': //calling the comments settings view $this->doView('settings/searches.php'); break; case 'latestsearches_post': // updating comment if (Params::getParam('save_latest_searches') == 'on') { Preference::newInstance()->update(array('s_value' => 1), array('s_name' => 'save_latest_searches')); } else { Preference::newInstance()->update(array('s_value' => 0), array('s_name' => 'save_latest_searches')); } Preference::newInstance()->update(array('s_value' => Params::getParam('customPurge')), array('s_name' => 'purge_latest_searches')); osc_add_flash_ok_message(_m('Settings have been updated'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=latestsearches'); break; default: // calling the view $aLanguages = OSCLocale::newInstance()->listAllEnabled(); $aCurrencies = Currency::newInstance()->listAll(); $this->_exportVariableToView('aLanguages', $aLanguages); $this->_exportVariableToView('aCurrencies', $aCurrencies); $this->doView('settings/index.php'); break; } }
function osc_downloadFile($sourceFile, $downloadedFile) { require_once LIB_PATH . 'libcurlemu/libcurlemu.inc.php'; @set_time_limit(0); $fp = @fopen(osc_content_path() . 'downloads/' . $downloadedFile, 'w+'); if ($fp) { $ch = curl_init($sourceFile); @curl_setopt($ch, CURLOPT_TIMEOUT, 50); curl_setopt($ch, CURLOPT_FILE, $fp); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); curl_close($ch); fclose($fp); return true; } else { return false; } }
// email_new_admin $comm->query(sprintf("INSERT INTO %st_pages (s_internal_name, b_indelible, dt_pub_date) VALUES ('email_new_admin', 1, '%s' )", DB_TABLE_PREFIX, date('Y-m-d H:i:s'))); $comm->query(sprintf("INSERT INTO %st_pages_description (fk_i_pages_id, fk_c_locale_code, s_title, s_text) VALUES (%d, 'en_US', '{WEB_TITLE} - Success creating admin account!', '<p>Hi {ADMIN_NAME},</p><p>The admin of {WEB_LINK} has created an account for you,</p><ul><li>Username: {USERNAME}</li><li>Password: {PASSWORD}</li></ul><p>You can access the admin panel here {WEB_ADMIN_LINK}.</p><p>Thank you!</p><p>Regards,</p>')", DB_TABLE_PREFIX, $comm->insertedId())); osc_set_preference('warn_expiration', '0', 'osclass', 'INTEGER'); $comm->query(sprintf("INSERT INTO %st_pages (s_internal_name, b_indelible, dt_pub_date) VALUES ('email_warn_expiration', 1, '%s' )", DB_TABLE_PREFIX, date('Y-m-d H:i:s'))); $comm->query(sprintf("INSERT INTO %st_pages_description (fk_i_pages_id, fk_c_locale_code, s_title, s_text) VALUES (%d, 'en_US', '{WEB_TITLE} - Your ad is about to expire', '<p>Hi {USER_NAME},</p><p>Your listing <a href=\"{ITEM_URL}\">{ITEM_TITLE}</a> is about to expire at {WEB_LINK}.')", DB_TABLE_PREFIX, $comm->insertedId())); osc_set_preference('force_aspect_image', '0', 'osclass', 'BOOLEAN'); } if (osc_version() < 321) { if (function_exists('osc_calculate_location_slug')) { osc_calculate_location_slug(osc_subdomain_type()); } } if (osc_version() < 330) { @mkdir(osc_content_path() . 'uploads/temp/'); @mkdir(osc_content_path() . 'downloads/oc-temp/', 0777); @unlink(osc_lib_path() . 'osclass/classes/Watermark.php'); osc_set_preference('title_character_length', '100', 'osclass', 'INTEGER'); osc_set_preference('description_character_length', '5000', 'osclass', 'INTEGER'); } if (osc_version() < 340) { $comm->query(sprintf("ALTER TABLE `%st_widget` ADD INDEX `idx_s_description` (`s_description`);", DB_TABLE_PREFIX)); osc_set_preference('force_jpeg', '0', 'osclass', 'BOOLEAN'); @unlink(ABS_PATH . '.maintenance'); // THESE LINES PROBABLY HIT LOW TIMEOUT SCRIPTS, RUN THE LAST OF THE UPGRADE PROCESS //osc_calculate_location_slug('country'); //osc_calculate_location_slug('region'); //osc_calculate_location_slug('city'); } if (osc_version() < 343) { // update t_alerts - Save them in plain json instead of base64
public function doWatermarkImage($filepath, $mime = 'image/png') { $path_watermark = osc_content_path() . 'uploads/watermark.png'; if (osc_use_imagick()) { $im = new Imagick($filepath); $wm = new Imagick($path_watermark); $geo = $im->getImageGeometry(); $wgeo = $wm->getImageGeometry(); switch (osc_watermark_place()) { case 'tl': $dest_x = 0; $dest_y = 0; break; case 'tr': $dest_x = $geo['width'] - $wgeo['width']; $dest_y = 0; break; case 'bl': $dest_x = 0; $dest_y = $geo['height'] - $wgeo['height']; break; case 'br': $dest_x = $geo['width'] - $wgeo['width']; $dest_y = $geo['height'] - $wgeo['height']; break; default: $dest_x = $geo['width'] / 2 - $wgeo['width'] / 2; $dest_y = $geo['height'] / 2 - $wgeo['height'] / 2; break; } $im->compositeImage($wm, imagick::COMPOSITE_OVER, $dest_x, $dest_y); $this->saveImageFile($im, 'image/jpeg', $filepath); $im->destroy(); $wm->destroy(); } else { $watermark = imagecreatefrompng($path_watermark); $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark); $image = imagecreatetruecolor($watermark_width, $watermark_height); $image = $this->getImageResource($filepath, $mime); $size = getimagesize($filepath); switch (osc_watermark_place()) { case 'tl': $dest_x = 0; $dest_y = 0; break; case 'tr': $dest_x = $size[0] - $watermark_width; $dest_y = 0; break; case 'bl': $dest_x = 0; $dest_y = $size[1] - $watermark_height; break; case 'br': $dest_x = $size[0] - $watermark_width; $dest_y = $size[1] - $watermark_height; break; default: $dest_x = $size[0] / 2 - $watermark_width / 2; $dest_y = $size[1] / 2 - $watermark_height / 2; break; } $this->imagecopymerge_alpha($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100); $this->saveImageFile($image, 'image/jpeg', $filepath); imagedestroy($image); imagedestroy($watermark); } }
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 'contact_post': //contact_post osc_csrf_check(); $yourName = Params::getParam('yourName'); $yourEmail = Params::getParam('yourEmail'); $subject = Params::getParam('subject'); $message = Params::getParam('message'); if (osc_recaptcha_private_key() != '') { if (!osc_check_recaptcha()) { osc_add_flash_error_message(_m('The Recaptcha code is wrong')); Session::newInstance()->_setForm('yourName', $yourName); Session::newInstance()->_setForm('yourEmail', $yourEmail); Session::newInstance()->_setForm('subject', $subject); Session::newInstance()->_setForm('message_body', $message); $this->redirectTo(osc_contact_url()); return false; // BREAK THE PROCESS, THE RECAPTCHA IS WRONG } } if (!preg_match('|.*?@.{2,}\\..{2,}|', $yourEmail)) { osc_add_flash_error_message(_m('Please enter a correct email')); Session::newInstance()->_setForm('yourName', $yourName); Session::newInstance()->_setForm('subject', $subject); Session::newInstance()->_setForm('message_body', $message); $this->redirectTo(osc_contact_url()); } $message_name = sprintf(__('Name: %s'), $yourName); $message_email = sprintf(__('Email: %s'), $yourEmail); $message_subject = sprintf(__('Subject: %s'), $subject); $message_body = sprintf(__('Message: %s'), $message); $message_date = sprintf(__('Date: %s at %s'), date('l F d, Y'), date('g:i a')); $message_IP = sprintf(__('IP Address: %s'), get_ip()); $message = <<<MESSAGE {$message_name} {$message_email} {$message_subject} {$message_body} {$message_date} {$message_IP} MESSAGE; $params = array('from' => osc_contact_email(), 'to' => osc_contact_email(), 'to_name' => osc_page_title(), 'reply_to' => $yourEmail, 'subject' => '[' . osc_page_title() . '] ' . __('Contact'), 'body' => nl2br($message)); if (osc_contact_attachment()) { $attachment = Params::getFiles('attachment'); if (isset($attachment['tmp_name'])) { $resourceName = $attachment['name']; $tmpName = $attachment['tmp_name']; $resourceType = $attachment['type']; $path = osc_content_path() . 'uploads/' . time() . '_' . $resourceName; if (!is_writable(osc_content_path() . 'uploads/')) { osc_add_flash_error_message(_m('There have been some errors sending the message')); $this->redirectTo(osc_contact_url()); } if (!move_uploaded_file($tmpName, $path)) { unset($path); } } } if (isset($path)) { $params['attachment'] = $path; } osc_run_hook('pre_contact_post', $params); osc_sendMail(osc_apply_filter('contact_params', $params)); osc_add_flash_ok_message(_m('Your email has been sent properly. Thank you for contacting us!')); $this->redirectTo(osc_contact_url()); break; default: //contact $this->doView('contact.php'); } }
function doModel() { //specific things for this class switch ($this->action) { case 'bulk_actions': break; case 'regions': //Return regions given a countryId $regions = Region::newInstance()->getByCountry(Params::getParam("countryId")); echo json_encode($regions); break; case 'cities': //Returns cities given a regionId $cities = City::newInstance()->getByRegion(Params::getParam("regionId")); echo json_encode($cities); break; case 'location': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term")); echo json_encode($cities); break; case 'alerts': // Allow to register to an alert given (not sure it's used on admin) $alert = Params::getParam("alert"); $email = Params::getParam("email"); $userid = Params::getParam("userid"); if ($alert != '' && $email != '') { Alerts::newInstance()->insert(array('fk_i_user_id' => $userid, 's_email' => $email, 's_search' => $alert, 'e_type' => 'DAILY')); echo "1"; return true; } echo '0'; return false; break; case 'runhook': //Run hooks $hook = Params::getParam("hook"); switch ($hook) { case 'item_form': $catId = Params::getParam("catId"); if ($catId != '') { osc_run_hook("item_form", $catId); } else { osc_run_hook("item_form"); } break; case 'item_edit': $catId = Params::getParam("catId"); $itemId = Params::getParam("itemId"); osc_run_hook("item_edit", $catId, $itemId); break; default: if ($hook == '') { return false; } else { osc_run_hook($hook); } break; } break; case 'items': // Return items (use external file oc-admin/ajax/item_processing.php) require_once osc_admin_base_path() . 'ajax/items_processing.php'; $items_processing = new items_processing_ajax(Params::getParamsAsArray("get")); break; case 'custom': // Execute via AJAX custom file $ajaxfile = Params::getParam("ajaxfile"); if ($ajaxfile != '') { require_once osc_admin_base_path() . $ajaxfile; } else { echo json_encode(array('error' => __('no action defined'))); } break; /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ case 'upgrade': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT $message = ""; $error = 0; $remove_error_msg = ""; $sql_error_msg = ""; $rm_errors = 0; $perms = osc_save_permissions(); osc_change_permissions(); /*********************** **** DOWNLOAD FILE **** ***********************/ if (Params::getParam('file') != '') { $tmp = explode("/", Params::getParam('file')); $filename = end($tmp); $result = osc_downloadFile(Params::getParam('file'), $filename); if ($result) { // Everything is OK, continue /********************** ***** UNZIP FILE ***** **********************/ @mkdir(ABS_PATH . 'oc-temp', 0777); $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/'); if ($res == 1) { // Everything is OK, continue /********************** ***** COPY FILES ***** **********************/ $fail = -1; if ($handle = opendir(ABS_PATH . 'oc-temp')) { $fail = 0; while (false !== ($_file = readdir($handle))) { if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') { $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file); if ($data == false) { $fail = 1; } } } closedir($handle); if ($fail == 0) { // Everything is OK, continue /********************** **** REMOVE FILES **** **********************/ if (file_exists(ABS_PATH . 'oc-temp/remove.list')) { $lines = file(ABS_PATH . 'oc-temp/remove.list', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($lines as $line_num => $r_file) { $unlink = @unlink(ABS_PATH . $r_file); if (!$unlink) { $remove_error_msg .= __('Error removing file: ') . $r_file . "<br/>"; } } } // Removing files is not important for the rest of the proccess // We will inform the user of the problems but the upgrade could continue /************************ *** UPGRADE DATABASE *** ************************/ $error_queries = array(); if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) { $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql'); $conn = getConnection(); $error_queries = $conn->osc_updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql)); } if ($error_queries[0]) { // Everything is OK, continue /********************************** ** EXECUTING ADDITIONAL ACTIONS ** **********************************/ if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) { // There should be no errors here require_once osc_lib_path() . 'osclass/upgrade-funcs.php'; } // Additional actions is not important for the rest of the proccess // We will inform the user of the problems but the upgrade could continue /**************************** ** REMOVE TEMPORARY FILES ** ****************************/ $path = ABS_PATH . 'oc-temp'; $rm_errors = 0; $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); for ($dir->rewind(); $dir->valid(); $dir->next()) { if ($dir->isDir()) { if ($dir->getFilename() != '.' && $dir->getFilename() != '..') { if (!rmdir($dir->getPathname())) { $rm_errors++; } } } else { if (!unlink($dir->getPathname())) { $rm_errors++; } } } if (!rmdir($path)) { $rm_errors++; } if ($rm_errors == 0) { $message = __('Everything was OK! Your OSClass installation is updated'); } else { $message = __('Almost everything was OK! Your OSClass installation is updated, but there were some errors removing temporary files. Please, remove manually the "oc-temp" folder', 'admin'); $error = 6; // Some errors removing files } } else { $sql_error_msg = $error_queries[2]; $message = __('Problems upgrading the database', 'admin'); $error = 5; // Problems upgrading the database } } else { $message = __('Problems copying files. Maybe permissions are not correct', 'admin'); $error = 4; // Problems copying files. Maybe permissions are not correct } } else { $message = __('Nothing to copy', 'admin'); $error = 99; // Nothing to copy. THIS SHOULD NEVER HAPPENS, means we dont update any file! } } else { $message = __('Unzip failed', 'admin'); $error = 3; // Unzip failed } } else { $message = __('Download failed', 'admin'); $error = 2; // Download failed } } else { $message = __('Missing download URL', 'admin'); $error = 1; // Missing download URL } if ($remove_error_msg != '') { if ($error == 0) { $message .= "<br /><br />" . __('We had some errors removing files, those are not super-sensitive errors, so we continued upgrading your installation. Please remove the following files (you already have OSClass upgraded, but to ensure maximun performance)', 'admin'); } } if ($error == 5) { $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed', 'admin') . implode("<br />", $sql_error_msg); } echo $message; foreach ($perms as $k => $v) { chmod($k, $v); } break; default: echo json_encode(array('error' => __('no action defined'))); break; } }
LatestSearches::newInstance()->purgeDate(date('Y-m-d H:i:s', time() - 3600)); } else { if (!in_array($purge, array('forever', 'day', 'week'))) { LatestSearches::newInstance()->purgeNumber($purge); } } osc_update_location_stats(true, 'auto'); // WARN EXPIRATION EACH HOUR (COMMENT TO DISABLE) // NOTE: IF THIS IS ENABLE, SAME CODE SHOULD BE DISABLE ON CRON DAILY if (is_numeric(osc_warn_expiration()) && osc_warn_expiration() > 0) { $items = Item::newInstance()->findByHourExpiration(24 * osc_warn_expiration()); foreach ($items as $item) { osc_run_hook('hook_email_warn_expiration', $item); } } $files = glob(osc_content_path() . 'uploads/temp/qqfile_*'); if (is_array($files)) { foreach ($files as $file) { if (time() - filectime($file) > 2 * 3600) { @unlink($file); } } } osc_run_hook('cron_hourly'); } } // Daily crons $cron = Cron::newInstance()->getCronByType('DAILY'); if (is_array($cron)) { $i_next = strtotime($cron['d_next_exec']); if (CLI && Params::getParam('cron-type') === 'daily' || $i_now - $i_next >= 0 && !CLI) {
function osc_market($section, $code) { $plugin = false; $re_enable = false; $message = ""; $data = array(); $download_post_data = array('api_key' => osc_market_api_connect()); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $url = osc_market_url($section, $code); $data = osc_file_get_contents($url, array('api_key' => osc_market_api_connect())); $data = json_decode(osc_file_get_contents($url, array('api_key' => osc_market_api_connect())), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $download_post_data = array(); $data = json_decode(osc_file_get_contents($code), true); } else { return array('error' => 9, 'message' => __('No external sources are allowed'), 'data' => $data); } } /*********************** **** 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 = date('YmdHis') . "_" . osc_sanitize_string($data['s_title']) . "_" . $data['s_version'] . ".zip"; $url_source_file = $data['s_source_file']; $result = osc_downloadFile($url_source_file, $filename, $download_post_data); if ($result) { // Everything is OK, continue /********************** ***** UNZIP FILE ***** **********************/ @mkdir(osc_content_path() . 'downloads/oc-temp/'); $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'); } } } else { if ($data['e_type'] == 'LANGUAGE') { osc_checkLocales(); } } // 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') { 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-content/downloads/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 { if (isset($data['s_buy_url']) && isset($data['b_paid']) && $data['s_buy_url'] != '' && $data['b_paid'] == 0) { $message = __('This is a paid item, you need to buy it before you are able to download it'); $error = 8; // Item not paid } else { $message = __('Input code not valid'); $error = 7; // Input code not valid } } } else { $message = __('Missing download URL'); $error = 1; // Missing download URL } return array('error' => $error, 'message' => $message, 'data' => $data); }
* modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program. If not, see <http://www.gnu.org/licenses/>. */ if (Params::getParam('plugin_action') == 'done') { $file = Params::getFiles('xml'); if (isset($file['error']) && $file['error'] == 0 && isset($file['size']) && $file['size'] > 0) { $tmpfile = osc_content_path() . 'uploads/adimporter_ads.temp'; @unlink($tmpfile); if (move_uploaded_file($file['tmp_name'], $tmpfile)) { $num_ads = adimporter_countads($tmpfile); } else { $num_ads = 0; } } else { osc_add_flash_error_message(__('File uploaded was not valid', 'adimporter'), 'admin'); osc_show_flash_message('admin'); $num_ads = 0; } if ($num_ads > 0) { ?> <script type="text/javascript">
function doModel() { switch ($this->action) { case 'comments': //calling the comments settings view $this->doView('settings/comments.php'); break; case 'comments_post': // updating comment $iUpdated = 0; $enabledComments = Params::getParam('enabled_comments'); $enabledComments = $enabledComments != '' ? true : false; $moderateComments = Params::getParam('moderate_comments'); $moderateComments = $moderateComments != '' ? true : false; $numModerateComments = Params::getParam('num_moderate_comments'); $commentsPerPage = Params::getParam('comments_per_page'); $notifyNewComment = Params::getParam('notify_new_comment'); $notifyNewComment = $notifyNewComment != '' ? true : false; $notifyNewCommentUser = Params::getParam('notify_new_comment_user'); $notifyNewCommentUser = $notifyNewCommentUser != '' ? true : false; $regUserPostComments = Params::getParam('reg_user_post_comments'); $regUserPostComments = $regUserPostComments != '' ? true : false; $msg = ''; if (!osc_validate_int(Params::getParam("num_moderate_comments"))) { $msg .= _m("Number of moderate comments must only contain numeric characters") . "<br/>"; } if (!osc_validate_int(Params::getParam("comments_per_page"))) { $msg .= _m("Comments per page must only contain numeric characters") . "<br/>"; } if ($msg != '') { osc_add_flash_error_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledComments), array('s_name' => 'enabled_comments')); if ($moderateComments) { $iUpdated += Preference::newInstance()->update(array('s_value' => $numModerateComments), array('s_name' => 'moderate_comments')); } else { $iUpdated += Preference::newInstance()->update(array('s_value' => '-1'), array('s_name' => 'moderate_comments')); } $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewComment), array('s_name' => 'notify_new_comment')); $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewCommentUser), array('s_name' => 'notify_new_comment_user')); $iUpdated += Preference::newInstance()->update(array('s_value' => $commentsPerPage), array('s_name' => 'comments_per_page')); $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserPostComments), array('s_name' => 'reg_user_post_comments')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m("Comment settings have been updated"), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments'); break; case 'locations': // calling the locations settings view $location_action = Params::getParam('type'); $mCountries = new Country(); switch ($location_action) { case 'add_country': // add country $countryCode = strtoupper(Params::getParam('c_country')); $countryName = Params::getParam('country'); $exists = $mCountries->findByCode($countryCode); if (isset($exists['s_name'])) { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $countryName), 'admin'); } else { $countries_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=country_code&term=' . urlencode($countryCode)); $countries = json_decode($countries_json); $mCountries->insert(array('pk_c_code' => $countryCode, 's_name' => $countryName)); CountryStats::newInstance()->setNumItems($countryCode, 0); if (isset($countries->error)) { // Country is not in our GEO database // We have no region for user-typed countries } else { // Country is in our GEO database, add regions and cities $manager_region = new Region(); $regions_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=region&country_code=' . urlencode($countryCode) . '&term=all'); $regions = json_decode($regions_json); if (!isset($regions->error)) { if (count($regions) > 0) { foreach ($regions as $r) { $manager_region->insert(array("fk_c_country_code" => $r->country_code, "s_name" => $r->name)); $id = $manager_region->dao->insertedId(); RegionStats::newInstance()->setNumItems($id, 0); } } unset($regions); unset($regions_json); $manager_city = new City(); if (count($countries) > 0) { foreach ($countries as $c) { $regions = $manager_region->findByCountry($c->id); if (!isset($regions->error)) { if (count($regions) > 0) { foreach ($regions as $region) { $cities_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=city&country=' . urlencode($c->name) . '®ion=' . urlencode($region['s_name']) . '&term=all'); $cities = json_decode($cities_json); if (!isset($cities->error)) { if (count($cities) > 0) { foreach ($cities as $ci) { $manager_city->insert(array("fk_i_region_id" => $region['pk_i_id'], "s_name" => $ci->name, "fk_c_country_code" => $ci->country_code)); $id = $manager_city->dao->insertedId(); CityStats::newInstance()->setNumItems($id, 0); } } } unset($cities); unset($cities_json); } } } } } } } osc_add_flash_ok_message(sprintf(_m('%s has been added as a new country'), $countryName), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'edit_country': // edit country $ok = $mCountries->update(array('s_name' => Params::getParam('e_country')), array('pk_c_code' => Params::getParam('country_code'))); if ($ok) { osc_add_flash_ok_message(_m('Country has been edited'), 'admin'); } else { osc_add_flash_error_message(_m('There were some problems editing the country'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'delete_country': // delete country $countryId = Params::getParam('id'); Item::newInstance()->deleteByRegion($countryId); $mRegions = new Region(); $mCities = new City(); $aCountries = $mCountries->findByCode($countryId); $aRegions = $mRegions->findByCountry($aCountries['pk_c_code']); foreach ($aRegions as $region) { // remove city_stats CityStats::newInstance()->deleteByRegion($region['pk_i_id']); // remove region_stats RegionStats::newInstance()->delete(array('fk_i_region_id' => $region['pk_i_id'])); } //remove country stats CountryStats::newInstance()->delete(array('fk_c_country_code' => $aCountries['pk_c_code'])); $ok = $mCountries->deleteByPrimaryKey($aCountries['pk_c_code']); if ($ok) { osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aCountries['s_name']), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('There was a problem deleting %s'), $aCountries['s_name']), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'add_region': // add region if (!Params::getParam('r_manual')) { $this->install_location_by_region(); } else { $mRegions = new Region(); $regionName = Params::getParam('region'); $countryCode = Params::getParam('country_c_parent'); $country = Country::newInstance()->findByCode($countryCode); $exists = $mRegions->findByName($regionName, $countryCode); if (!isset($exists['s_name'])) { $data = array('fk_c_country_code' => $countryCode, 's_name' => $regionName); $mRegions->insert($data); $id = $mRegions->dao->insertedId(); RegionStats::newInstance()->setNumItems($id, 0); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new region'), $regionName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $regionName), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$countryCode . "&country=" . @$country['s_name']); break; case 'edit_region': // edit region $mRegions = new Region(); $newRegion = Params::getParam('e_region'); $regionId = Params::getParam('region_id'); $exists = $mRegions->findByName($newRegion); if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $regionId) { if ($regionId != '') { $aRegion = $mRegions->findByPrimaryKey($regionId); $country = Country::newInstance()->findByCode($aRegion['fk_c_country_code']); $mRegions->update(array('s_name' => $newRegion), array('pk_i_id' => $regionId)); ItemLocation::newInstance()->update(array('s_region' => $newRegion), array('fk_i_region_id' => $regionId)); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newRegion), 'admin'); } } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newRegion), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name']); break; case 'delete_region': // delete region $mRegion = new Region(); $mCities = new City(); $regionId = Params::getParam('id'); if ($regionId != '') { Item::newInstance()->deleteByRegion($regionId); $aRegion = $mRegion->findByPrimaryKey($regionId); $country = Country::newInstance()->findByCode($aRegion['fk_c_country_code']); // remove city_stats CityStats::newInstance()->deleteByRegion($regionId); $mCities->delete(array('fk_i_region_id' => $regionId)); // remove region_stats RegionStats::newInstance()->delete(array('fk_i_region_id' => $regionId)); $mRegion->delete(array('pk_i_id' => $regionId)); osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aRegion['s_name']), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name']); break; case 'add_city': // add city $mRegion = new Region(); $mCities = new City(); $regionId = Params::getParam('region_parent'); $countryCode = Params::getParam('country_c_parent'); $newCity = Params::getParam('city'); $exists = $mCities->findByName($newCity, $regionId); $region = $mRegion->findByPrimaryKey($regionId); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); if (!isset($exists['s_name'])) { $mCities->insert(array('fk_i_region_id' => $regionId, 's_name' => $newCity, 'fk_c_country_code' => $countryCode)); $id = $mCities->dao->insertedId(); CityStats::newInstance()->setNumItems($id, 0); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new city'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "®ion=" . $regionId); break; case 'edit_city': // edit city $mRegion = new Region(); $mCities = new City(); $newCity = Params::getParam('e_city'); $cityId = Params::getParam('city_id'); $exists = $mCities->findByName($newCity); if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $cityId) { $city = $mCities->findByPrimaryKey($cityId); $region = $mRegion->findByPrimaryKey($city['fk_i_region_id']); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); $mCities->update(array('s_name' => $newCity), array('pk_i_id' => $cityId)); ItemLocation::newInstance()->update(array('s_city' => $newCity), array('fk_i_city_id' => $cityId)); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "®ion=" . @$region['pk_i_id']); break; case 'delete_city': // delete city $mRegion = new Region(); $mCities = new City(); $cityId = Params::getParam('id'); Item::newInstance()->deleteByCity($cityId); $aCity = $mCities->findByPrimaryKey($cityId); // remove region_stats $region = $mRegion->findByPrimaryKey($aCity['fk_i_region_id']); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); CityStats::newInstance()->delete(array('fk_i_city_id' => $cityId)); $mCities->delete(array('pk_i_id' => $cityId)); osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aCity['s_name']), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "®ion=" . @$region['pk_i_id']); break; } $aCountries = $mCountries->listAll(); $this->_exportVariableToView('aCountries', $aCountries); $this->doView('settings/locations.php'); break; case 'permalinks': // calling the permalinks view $htaccess = Params::getParam('htaccess_status'); $file = Params::getParam('file_status'); $this->_exportVariableToView('htaccess', $htaccess); $this->_exportVariableToView('file', $file); $this->doView('settings/permalinks.php'); break; case 'permalinks_post': // updating permalinks option $htaccess_file = osc_base_path() . '.htaccess'; $rewriteEnabled = Params::getParam('rewrite_enabled') ? true : false; if ($rewriteEnabled) { Preference::newInstance()->update(array('s_value' => '1'), array('s_name' => 'rewriteEnabled')); $rewrite_base = REL_WEB_URL; $htaccess = <<<HTACCESS <IfModule mod_rewrite.c> RewriteEngine On RewriteBase {$rewrite_base} RewriteRule ^index\\.php\$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . {$rewrite_base}index.php [L] </IfModule> HTACCESS; // 1. OK (ok) // 2. OK no apache module detected (warning) // 3. No se puede crear + apache // 4. No se puede crear + no apache $status = 3; if (file_exists($htaccess_file)) { if (is_writable($htaccess_file) && file_put_contents($htaccess_file, $htaccess)) { $status = 1; } } else { if (is_writable(osc_base_path()) && file_put_contents($htaccess_file, $htaccess)) { $status = 1; } } if (!@apache_mod_loaded('mod_rewrite')) { $status++; } $errors = 0; $item_url = substr(str_replace('//', '/', Params::getParam('rewrite_item_url') . '/'), 0, -1); if (!osc_validate_text($item_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $item_url), array('s_name' => 'rewrite_item_url')); } $page_url = substr(str_replace('//', '/', Params::getParam('rewrite_page_url') . '/'), 0, -1); if (!osc_validate_text($page_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $page_url), array('s_name' => 'rewrite_page_url')); } $cat_url = substr(str_replace('//', '/', Params::getParam('rewrite_cat_url') . '/'), 0, -1); if (!osc_validate_text($cat_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $cat_url), array('s_name' => 'rewrite_cat_url')); } $search_url = substr(str_replace('//', '/', Params::getParam('rewrite_search_url') . '/'), 0, -1); if (!osc_validate_text($search_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $search_url), array('s_name' => 'rewrite_search_url')); } if (!osc_validate_text(Params::getParam('rewrite_search_country'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_country')), array('s_name' => 'rewrite_search_country')); } if (!osc_validate_text(Params::getParam('rewrite_search_region'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_region')), array('s_name' => 'rewrite_search_region')); } if (!osc_validate_text(Params::getParam('rewrite_search_city'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_city')), array('s_name' => 'rewrite_search_city')); } if (!osc_validate_text(Params::getParam('rewrite_search_city_area'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_city_area')), array('s_name' => 'rewrite_search_city_area')); } if (!osc_validate_text(Params::getParam('rewrite_search_category'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_category')), array('s_name' => 'rewrite_search_category')); } if (!osc_validate_text(Params::getParam('rewrite_search_user'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_user')), array('s_name' => 'rewrite_search_user')); } if (!osc_validate_text(Params::getParam('rewrite_search_pattern'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_pattern')), array('s_name' => 'rewrite_search_pattern')); } $rewrite_contact = substr(str_replace('//', '/', Params::getParam('rewrite_contact') . '/'), 0, -1); if (!osc_validate_text($rewrite_contact)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_contact), array('s_name' => 'rewrite_contact')); } $rewrite_feed = substr(str_replace('//', '/', Params::getParam('rewrite_feed') . '/'), 0, -1); if (!osc_validate_text($rewrite_feed)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_feed), array('s_name' => 'rewrite_feed')); } $rewrite_language = substr(str_replace('//', '/', Params::getParam('rewrite_language') . '/'), 0, -1); if (!osc_validate_text($rewrite_language)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_language), array('s_name' => 'rewrite_language')); } $rewrite_item_mark = substr(str_replace('//', '/', Params::getParam('rewrite_item_mark') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_mark)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_mark), array('s_name' => 'rewrite_item_mark')); } $rewrite_item_send_friend = substr(str_replace('//', '/', Params::getParam('rewrite_item_send_friend') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_send_friend)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_send_friend), array('s_name' => 'rewrite_item_send_friend')); } $rewrite_item_contact = substr(str_replace('//', '/', Params::getParam('rewrite_item_contact') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_contact)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_contact), array('s_name' => 'rewrite_item_contact')); } $rewrite_item_new = substr(str_replace('//', '/', Params::getParam('rewrite_item_new') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_new)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_new), array('s_name' => 'rewrite_item_new')); } $rewrite_item_activate = substr(str_replace('//', '/', Params::getParam('rewrite_item_activate') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_activate)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_activate), array('s_name' => 'rewrite_item_activate')); } $rewrite_item_edit = substr(str_replace('//', '/', Params::getParam('rewrite_item_edit') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_edit)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_edit), array('s_name' => 'rewrite_item_edit')); } $rewrite_item_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_delete') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_delete)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_delete), array('s_name' => 'rewrite_item_delete')); } $rewrite_item_resource_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_resource_delete') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_resource_delete)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_resource_delete), array('s_name' => 'rewrite_item_resource_delete')); } $rewrite_user_login = substr(str_replace('//', '/', Params::getParam('rewrite_user_login') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_login)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_login), array('s_name' => 'rewrite_user_login')); } $rewrite_user_dashboard = substr(str_replace('//', '/', Params::getParam('rewrite_user_dashboard') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_dashboard)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_dashboard), array('s_name' => 'rewrite_user_dashboard')); } $rewrite_user_logout = substr(str_replace('//', '/', Params::getParam('rewrite_user_logout') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_logout)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_logout), array('s_name' => 'rewrite_user_logout')); } $rewrite_user_register = substr(str_replace('//', '/', Params::getParam('rewrite_user_register') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_register)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_register), array('s_name' => 'rewrite_user_register')); } $rewrite_user_activate = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_activate)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_activate), array('s_name' => 'rewrite_user_activate')); } $rewrite_user_activate_alert = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate_alert') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_activate_alert)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_activate_alert), array('s_name' => 'rewrite_user_activate_alert')); } $rewrite_user_profile = substr(str_replace('//', '/', Params::getParam('rewrite_user_profile') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_profile)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_profile), array('s_name' => 'rewrite_user_profile')); } $rewrite_user_items = substr(str_replace('//', '/', Params::getParam('rewrite_user_items') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_items)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_items), array('s_name' => 'rewrite_user_items')); } $rewrite_user_alerts = substr(str_replace('//', '/', Params::getParam('rewrite_user_alerts') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_alerts)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_alerts), array('s_name' => 'rewrite_user_alerts')); } $rewrite_user_recover = substr(str_replace('//', '/', Params::getParam('rewrite_user_recover') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_recover)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_recover), array('s_name' => 'rewrite_user_recover')); } $rewrite_user_forgot = substr(str_replace('//', '/', Params::getParam('rewrite_user_forgot') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_forgot)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_forgot), array('s_name' => 'rewrite_user_forgot')); } $rewrite_user_change_password = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_password') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_change_password)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_change_password), array('s_name' => 'rewrite_user_change_password')); } $rewrite_user_change_email = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_change_email)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_change_email), array('s_name' => 'rewrite_user_change_email')); } $rewrite_user_change_email_confirm = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email_confirm') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_change_email_confirm)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_change_email_confirm), array('s_name' => 'rewrite_user_change_email_confirm')); } osc_reset_preferences(); $rewrite = Rewrite::newInstance(); osc_run_hook("before_rewrite_rules", array(&$rewrite)); $rewrite->clearRules(); /***************************** ********* Add rules ********* *****************************/ // Contact rules $rewrite->addRule('^' . osc_get_preference('rewrite_contact') . '/?$', 'index.php?page=contact'); // Feed rules $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/?$', 'index.php?page=search&sFeed=rss'); $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/(.+)/?$', 'index.php?page=search&sFeed=$1'); // Language rules $rewrite->addRule('^' . osc_get_preference('rewrite_language') . '/(.*?)/?$', 'index.php?page=language&locale=$1'); // Search rules $rewrite->addRule('^' . $search_url . '$', 'index.php?page=search'); $rewrite->addRule('^' . $search_url . '/(.*)$', 'index.php?page=search&sParams=$1'); // Item rules $rewrite->addRule('^' . osc_get_preference('rewrite_item_mark') . '/(.*?)/([0-9]+)/?$', 'index.php?page=item&action=mark&as=$1&id=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_send_friend') . '/([0-9]+)/?$', 'index.php?page=item&action=send_friend&id=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_contact') . '/([0-9]+)/?$', 'index.php?page=item&action=contact&id=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/?$', 'index.php?page=item&action=item_add'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/([0-9]+)/?$', 'index.php?page=item&action=item_add&catId=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=activate&id=$1&secret=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_edit') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_edit&id=$1&secret=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_delete') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_delete&id=$1&secret=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_resource_delete') . '/([0-9]+)/([0-9]+)/([0-9A-Za-z]+)/?(.*?)/?$', 'index.php?page=item&action=deleteResource&id=$1&item=$2&code=$3&secret=$4'); // Item rules $id_pos = stripos($item_url, '{ITEM_ID}'); $title_pos = stripos($item_url, '{ITEM_TITLE}'); $cat_pos = stripos($item_url, '{CATEGORIES'); $param_pos = 1; if ($title_pos !== false && $id_pos > $title_pos) { $param_pos++; } if ($cat_pos !== false && $id_pos > $cat_pos) { $param_pos++; } $comments_pos = 1; if ($id_pos !== false) { $comments_pos++; } if ($title_pos !== false) { $comments_pos++; } if ($cat_pos !== false) { $comments_pos++; } $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$1&comments-page=$2'); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$3&lang=$1_$2&comments-page=$4'); $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$1'); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$3&lang=$1_$2'); // User rules $rewrite->addRule('^' . osc_get_preference('rewrite_user_login') . '/?$', 'index.php?page=login'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_dashboard') . '/?$', 'index.php?page=user&action=dashboard'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_logout') . '/?$', 'index.php?page=main&action=logout'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_register') . '/?$', 'index.php?page=register&action=register'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=register&action=validate&id=$1&code=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate_alert') . '/([a-zA-Z0-9]+)/(.+)$', 'index.php?page=user&action=activate_alert&email=$2&secret=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/?$', 'index.php?page=user&action=profile'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/([0-9]+)/?$', 'index.php?page=user&action=pub_profile&id=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_items') . '/?$', 'index.php?page=user&action=items'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_alerts') . '/?$', 'index.php?page=user&action=alerts'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_recover') . '/?$', 'index.php?page=login&action=recover'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_forgot') . '/([0-9]+)/(.*)/?$', 'index.php?page=login&action=forgot&userId=$1&code=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_password') . '/?$', 'index.php?page=user&action=change_password'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email') . '/?$', 'index.php?page=user&action=change_email'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email_confirm') . '/([0-9]+)/(.*?)/?$', 'index.php?page=user&action=change_email_confirm&userId=$1&code=$2'); // Page rules $pos_pID = stripos($page_url, '{PAGE_ID}'); $pos_pSlug = stripos($page_url, '{PAGE_SLUG}'); $pID_pos = 1; $pSlug_pos = 1; if (is_numeric($pos_pID) && is_numeric($pos_pSlug)) { // set the order of the parameters if ($pos_pID > $pos_pSlug) { $pID_pos++; } else { $pSlug_pos++; } $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&id=$' . $pID_pos . "&slug=\$" . $pSlug_pos); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&lang=$1_$2&id=$' . ($pID_pos + 2) . '&slug=$' . ($pSlug_pos + 2)); } else { if (is_numeric($pos_pID)) { $rewrite->addRule('^' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&id=$1'); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&id=$3'); } else { $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&slug=$1'); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&slug=$3'); } } // Clean archive files $rewrite->addRule('^(.+?)\\.php(.*)$', '$1.php$2'); // Category rules $id_pos = stripos($item_url, '{CATEGORY_ID}'); $title_pos = stripos($item_url, '{CATEGORY_SLUG}'); $cat_pos = stripos($item_url, '{CATEGORIES'); $param_pos = 1; if ($title_pos !== false && $id_pos > $title_pos) { $param_pos++; } if ($cat_pos !== false && $id_pos > $cat_pos) { $param_pos++; } $rewrite->addRule('^' . str_replace('{CATEGORIES}', '(.+)', str_replace('{CATEGORY_SLUG}', '([^/]+)', str_replace('{CATEGORY_ID}', '([0-9]+)', $cat_url))) . '$', 'index.php?page=search&sCategory=$' . $param_pos); osc_run_hook("after_rewrite_rules", array(&$rewrite)); //Write rule to DB $rewrite->setRules(); $msg_error = '<br/>' . _m('All fields are required.') . " " . sprintf(_mn('One field was not updated', '%s fields were not updated', $errors), $errors); switch ($status) { case 1: $msg = _m("Permalinks structure updated"); if ($errors > 0) { $msg .= $msg_error; osc_add_flash_warning_message($msg, 'admin'); } else { osc_add_flash_ok_message($msg, 'admin'); } break; case 2: $msg = _m("Permalinks structure updated."); $msg .= " "; $msg .= _m("However, we can't check if Apache module <b>mod_rewrite</b> is loaded. If you experience some problems with the URLs, you should deactivate <em>Friendly URLs</em>"); if ($errors > 0) { $msg .= $msg_error; } osc_add_flash_warning_message($msg, 'admin'); break; case 3: $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content."); $msg .= " "; $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file, please deactivate the <em>Friendly URLs</em> option."); $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>'; if ($errors > 0) { $msg .= $msg_error; } osc_add_flash_error_message($msg, 'admin'); break; case 4: $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content."); $msg .= " "; $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file or experience some problems with the URLs, please deactivate the <em>Friendly URLs</em> option."); $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>'; if ($errors > 0) { $msg .= $msg_error; } osc_add_flash_error_message($msg, 'admin'); break; } } else { Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'rewriteEnabled')); Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'mod_rewrite_loaded')); osc_add_flash_ok_message(_m('Friendly URLs successfully deactivated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=permalinks'); break; case 'spamNbots': // calling the spam and bots view $akismet_key = osc_akismet_key(); $akismet_status = 3; if ($akismet_key != '') { require_once osc_lib_path() . 'Akismet.class.php'; $akismet_obj = new Akismet(osc_base_url(), $akismet_key); $akismet_status = 2; if ($akismet_obj->isKeyValid()) { $akismet_status = 1; } } View::newInstance()->_exportVariableToView('akismet_status', $akismet_status); $this->doView('settings/spamNbots.php'); break; case 'akismet_post': // updating spam and bots option $updated = 0; $akismetKey = Params::getParam('akismetKey'); $akismetKey = trim($akismetKey); $updated = Preference::newInstance()->update(array('s_value' => $akismetKey), array('s_name' => 'akismetKey')); if ($akismetKey == '') { osc_add_flash_info_message(_m('Your Akismet key has been cleared'), 'admin'); } else { osc_add_flash_ok_message(_m('Your Akismet key has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=spamNbots'); break; case 'recaptcha_post': // updating spam and bots option $iUpdated = 0; $recaptchaPrivKey = Params::getParam('recaptchaPrivKey'); $recaptchaPrivKey = trim($recaptchaPrivKey); $recaptchaPubKey = Params::getParam('recaptchaPubKey'); $recaptchaPubKey = trim($recaptchaPubKey); $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPrivKey), array('s_name' => 'recaptchaPrivKey')); $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPubKey), array('s_name' => 'recaptchaPubKey')); if ($recaptchaPubKey == '') { osc_add_flash_info_message(_m('Your reCAPTCHA key has been cleared'), 'admin'); } else { osc_add_flash_ok_message(_m('Your reCAPTCHA key has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=spamNbots'); break; case 'currencies': // currencies settings $currencies_action = Params::getParam('type'); switch ($currencies_action) { case 'add': // calling add currency view $aCurrency = array('pk_c_code' => '', 's_name' => '', 's_description' => ''); $this->_exportVariableToView('aCurrency', $aCurrency); $this->_exportVariableToView('typeForm', 'add_post'); $this->doView('settings/currency_form.php'); break; case 'add_post': // adding a new currency $currencyCode = Params::getParam('pk_c_code'); $currencyName = Params::getParam('s_name'); $currencyDescription = Params::getParam('s_description'); // cleaning parameters $currencyName = strip_tags($currencyName); $currencyDescription = strip_tags($currencyDescription); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if (!preg_match('/^.{1,3}$/', $currencyCode)) { osc_add_flash_error_message(_m('The currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $fields = array('pk_c_code' => $currencyCode, 's_name' => $currencyName, 's_description' => $currencyDescription); $isInserted = Currency::newInstance()->insert($fields); if ($isInserted) { osc_add_flash_ok_message(_m('Currency added'), 'admin'); } else { osc_add_flash_error_message(_m("Currency couldn't be added"), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; case 'edit': // calling edit currency view $currencyCode = Params::getParam('code'); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if ($currencyCode == '') { osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $aCurrency = Currency::newInstance()->findByPrimaryKey($currencyCode); if (!$aCurrency) { osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $this->_exportVariableToView('aCurrency', $aCurrency); $this->_exportVariableToView('typeForm', 'edit_post'); $this->doView('settings/currency_form.php'); break; case 'edit_post': // updating currency $currencyName = Params::getParam('s_name'); $currencyDescription = Params::getParam('s_description'); $currencyCode = Params::getParam('pk_c_code'); // cleaning parameters $currencyName = strip_tags($currencyName); $currencyDescription = strip_tags($currencyDescription); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if (!preg_match('/.{1,3}/', $currencyCode)) { osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $updated = Currency::newInstance()->update(array('s_name' => $currencyName, 's_description' => $currencyDescription), array('pk_c_code' => $currencyCode)); if ($updated == 1) { osc_add_flash_ok_message(_m('Currency updated'), 'admin'); } else { osc_add_flash_info_message(_m('No changes were made'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; case 'delete': // deleting a currency $rowChanged = 0; $aCurrencyCode = Params::getParam('code'); if (!is_array($aCurrencyCode)) { $aCurrencyCode = array($aCurrencyCode); } $msg_current = ''; foreach ($aCurrencyCode as $currencyCode) { if (preg_match('/.{1,3}/', $currencyCode) && $currencyCode != osc_currency()) { $rowChanged += Currency::newInstance()->delete(array('pk_c_code' => $currencyCode)); } // foreign key error if (Currency::newInstance()->getErrorLevel() == '1451') { $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it has listings associated to it"), $currencyCode); } else { if ($currencyCode == osc_currency()) { $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it's the default currency"), $currencyCode); } } } $msg = ''; $status = ''; switch ($rowChanged) { case '0': $msg = _m('No currencies have been deleted'); $status = 'error'; break; case '1': $msg = _m('One currency has been deleted'); $status = 'ok'; break; default: $msg = sprintf(_m('%s currencies have been deleted'), $rowChanged); $status = 'ok'; break; } if ($status == 'ok' && $msg_current != '') { $status = 'warning'; } switch ($status) { case 'error': osc_add_flash_error_message($msg . $msg_current, 'admin'); break; case 'warning': osc_add_flash_warning_message($msg . $msg_current, 'admin'); break; case 'ok': osc_add_flash_ok_message($msg, 'admin'); break; } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; default: // calling the currencies view $aCurrencies = Currency::newInstance()->listAll(); $this->_exportVariableToView('aCurrencies', $aCurrencies); $this->doView('settings/currencies.php'); break; } break; case 'mailserver': // calling the mailserver view $this->doView('settings/mailserver.php'); break; case 'mailserver_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); } // updating mailserver $iUpdated = 0; $mailserverAuth = Params::getParam('mailserver_auth'); $mailserverAuth = $mailserverAuth != '' ? true : false; $mailserverPop = Params::getParam('mailserver_pop'); $mailserverPop = $mailserverPop != '' ? true : false; $mailserverType = Params::getParam('mailserver_type'); $mailserverHost = Params::getParam('mailserver_host'); $mailserverPort = Params::getParam('mailserver_port'); $mailserverUsername = Params::getParam('mailserver_username'); $mailserverPassword = Params::getParam('mailserver_password'); $mailserverSsl = Params::getParam('mailserver_ssl'); if (!in_array($mailserverType, array('custom', 'gmail'))) { osc_add_flash_error_message(_m('Mail server type is incorrect'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverAuth), array('s_name' => 'mailserver_auth')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPop), array('s_name' => 'mailserver_pop')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverType), array('s_name' => 'mailserver_type')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverHost), array('s_name' => 'mailserver_host')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPort), array('s_name' => 'mailserver_port')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverUsername), array('s_name' => 'mailserver_username')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPassword), array('s_name' => 'mailserver_password')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverSsl), array('s_name' => 'mailserver_ssl')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Mail server configuration has changed'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); break; case 'media': // calling the media view $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $memory_limit = (int) ini_get('memory_limit'); $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024; $this->_exportVariableToView('max_size_upload', $upload_mb); $this->doView('settings/media.php'); break; case 'media_post': // updating the media config $status = 'ok'; $error = ''; $iUpdated = 0; $maxSizeKb = Params::getParam('maxSizeKb'); $allowedExt = Params::getParam('allowedExt'); $dimThumbnail = Params::getParam('dimThumbnail'); $dimPreview = Params::getParam('dimPreview'); $dimNormal = Params::getParam('dimNormal'); $keepOriginalImage = Params::getParam('keep_original_image'); $use_imagick = Params::getParam('use_imagick'); $type_watermark = Params::getParam('watermark_type'); $watermark_color = Params::getParam('watermark_text_color'); $watermark_text = Params::getParam('watermark_text'); switch ($type_watermark) { case 'none': $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image')); break; case 'text': $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_color), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_text), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image')); $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_text_place')), array('s_name' => 'watermark_place')); break; case 'image': // upload image & move to path if ($_FILES['watermark_image']['error'] == UPLOAD_ERR_OK) { if ($_FILES['watermark_image']['type'] == 'image/png') { $tmpName = $_FILES['watermark_image']['tmp_name']; $path = osc_content_path() . 'uploads/watermark.png'; if (move_uploaded_file($tmpName, $path)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $path), array('s_name' => 'watermark_image')); } else { $error .= _m('There was a problem uploading the watermark image') . "<br />"; } } else { $error .= _m('The watermark image has to be a .PNG file') . "<br />"; } } else { $error .= _m('There was a problem uploading the watermark image') . "<br />"; } $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_image_place')), array('s_name' => 'watermark_place')); break; default: break; } // format parameters $maxSizeKb = strip_tags($maxSizeKb); $allowedExt = strip_tags($allowedExt); $dimThumbnail = strip_tags($dimThumbnail); $dimPreview = strip_tags($dimPreview); $dimNormal = strip_tags($dimNormal); $keepOriginalImage = $keepOriginalImage != '' ? true : false; $use_imagick = $use_imagick != '' ? true : false; // is imagick extension loaded? if (!@extension_loaded('imagick')) { $use_imagick = false; } // max size allowed by PHP configuration? $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $memory_limit = (int) ini_get('memory_limit'); $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024; // set maxSizeKB equals to PHP configuration if it's bigger if ($maxSizeKb > $upload_mb) { $status = 'warning'; $maxSizeKb = $upload_mb; // flash message text warning $error .= sprintf(_m("You cannot set a maximum file size higher than the one allowed in the PHP configuration: <b>%d KB</b>"), $upload_mb); } $iUpdated += Preference::newInstance()->update(array('s_value' => $maxSizeKb), array('s_name' => 'maxSizeKb')); $iUpdated += Preference::newInstance()->update(array('s_value' => $allowedExt), array('s_name' => 'allowedExt')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimThumbnail), array('s_name' => 'dimThumbnail')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimPreview), array('s_name' => 'dimPreview')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimNormal), array('s_name' => 'dimNormal')); $iUpdated += Preference::newInstance()->update(array('s_value' => $keepOriginalImage), array('s_name' => 'keep_original_image')); $iUpdated += Preference::newInstance()->update(array('s_value' => $use_imagick), array('s_name' => 'use_imagick')); if ($error != '') { switch ($status) { case 'error': osc_add_flash_error_message($error, 'admin'); break; case 'warning': osc_add_flash_warning_message($error, 'admin'); break; default: osc_add_flash_ok_message($error, 'admin'); break; } } else { osc_add_flash_ok_message(_m('Media config has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); break; case 'images_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); } $wat = new Watermark(); $aResources = ItemResource::newInstance()->getAllResources(); foreach ($aResources as $resource) { osc_run_hook('regenerate_image', $resource); $path = osc_content_path() . 'uploads/'; // comprobar que no haya original $img_original = $path . $resource['pk_i_id'] . "_original*"; $aImages = glob($img_original); // there is original image if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_normal = $path . $resource['pk_i_id'] . ".*"; $aImages = glob($img_normal); if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_thumbnail = $path . $resource['pk_i_id'] . "_thumbnail*"; $aImages = glob($img_thumbnail); $image_tmp = $aImages[0]; } } // extension preg_match('/\\.(.*)$/', $image_tmp, $matches); if (isset($matches[1])) { $extension = $matches[1]; // Create normal size $path_normal = $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '.jpg'; $size = explode('x', osc_normal_dimensions()); ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1])->saveToFile($path); if (osc_is_watermark_text()) { $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg'); } elseif (osc_is_watermark_image()) { $wat->doWatermarkImage($path, 'image/jpeg'); } // Create preview $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_preview.jpg'; $size = explode('x', osc_preview_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // Create thumbnail $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_thumbnail.jpg'; $size = explode('x', osc_thumbnail_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // update resource info ItemResource::newInstance()->update(array('s_path' => 'oc-content/uploads/', 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => 'image/jpeg'), array('pk_i_id' => $resource['pk_i_id'])); osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id'])); // si extension es direfente a jpg, eliminar las imagenes con $extension si hay if ($extension != 'jpg') { @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "." . $extension); @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_original." . $extension); @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_preview." . $extension); @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_thumbnail." . $extension); } // .... } else { // no es imagen o imagen sin extesión } } osc_add_flash_ok_message(_m('Re-generation complete'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); break; case 'update': // update index view $iUpdated = 0; $sPageTitle = Params::getParam('pageTitle'); $sPageDesc = Params::getParam('pageDesc'); $sContactEmail = Params::getParam('contactEmail'); $sLanguage = Params::getParam('language'); $sDateFormat = Params::getParam('dateFormat'); $sCurrency = Params::getParam('currency'); $sWeekStart = Params::getParam('weekStart'); $sTimeFormat = Params::getParam('timeFormat'); $sTimezone = Params::getParam('timezone'); $sNumRssItems = Params::getParam('num_rss_items'); $maxLatestItems = Params::getParam('max_latest_items_at_home'); $numItemsSearch = Params::getParam('default_results_per_page'); $contactAttachment = Params::getParam('enabled_attachment'); $selectableParent = Params::getParam('selectable_parent_categories'); $bAutoCron = Params::getParam('auto_cron'); $bMarketSources = Params::getParam('market_external_sources') == 1 ? 1 : 0; // preparing parameters $sPageTitle = strip_tags($sPageTitle); $sPageDesc = strip_tags($sPageDesc); $sContactEmail = strip_tags($sContactEmail); $sLanguage = strip_tags($sLanguage); $sDateFormat = strip_tags($sDateFormat); $sCurrency = strip_tags($sCurrency); $sWeekStart = strip_tags($sWeekStart); $sTimeFormat = strip_tags($sTimeFormat); $sNumRssItems = (int) strip_tags($sNumRssItems); $maxLatestItems = (int) strip_tags($maxLatestItems); $numItemsSearch = (int) $numItemsSearch; $contactAttachment = $contactAttachment != '' ? true : false; $bAutoCron = $bAutoCron != '' ? true : false; $error = ""; $msg = ''; if (!osc_validate_text($sPageTitle)) { $msg .= _m("Page title field is required") . "<br/>"; } if (!osc_validate_text($sContactEmail)) { $msg .= _m("Contact email field is required") . "<br/>"; } if (!osc_validate_int($sNumRssItems)) { $msg .= _m("Number of listings in the RSS has to be a numeric value") . "<br/>"; } if (!osc_validate_int($maxLatestItems)) { $msg .= _m("Max latest listings has to be a numeric value") . "<br/>"; } if (!osc_validate_int($numItemsSearch)) { $msg .= _m("Number of listings on search has to be a numeric value") . "<br/>"; } if ($msg != '') { osc_add_flash_error_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageTitle), array('s_section' => 'osclass', 's_name' => 'pageTitle')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageDesc), array('s_section' => 'osclass', 's_name' => 'pageDesc')); if (!defined('DEMO')) { $iUpdated += Preference::newInstance()->update(array('s_value' => $sContactEmail), array('s_section' => 'osclass', 's_name' => 'contactEmail')); } $iUpdated += Preference::newInstance()->update(array('s_value' => $sLanguage), array('s_section' => 'osclass', 's_name' => 'language')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sDateFormat), array('s_section' => 'osclass', 's_name' => 'dateFormat')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sCurrency), array('s_section' => 'osclass', 's_name' => 'currency')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sWeekStart), array('s_section' => 'osclass', 's_name' => 'weekStart')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimeFormat), array('s_section' => 'osclass', 's_name' => 'timeFormat')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimezone), array('s_section' => 'osclass', 's_name' => 'timezone')); $iUpdated += Preference::newInstance()->update(array('s_value' => $bMarketSources), array('s_section' => 'osclass', 's_name' => 'marketAllowExternalSources')); if (is_int($sNumRssItems)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $sNumRssItems), array('s_section' => 'osclass', 's_name' => 'num_rss_items')); } else { if ($error != '') { $error .= "</p><p>"; } $error .= _m('Number of listings in the RSS must be an integer'); } if (is_int($maxLatestItems)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $maxLatestItems), array('s_section' => 'osclass', 's_name' => 'maxLatestItems@home')); } else { if ($error != '') { $error .= "</p><p>"; } $error .= _m('Number of recent listings displayed at home must be an integer'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $numItemsSearch), array('s_section' => 'osclass', 's_name' => 'defaultResultsPerPage@search')); $iUpdated += Preference::newInstance()->update(array('s_value' => $contactAttachment), array('s_name' => 'contact_attachment')); $iUpdated += Preference::newInstance()->update(array('s_value' => $bAutoCron), array('s_name' => 'auto_cron')); $iUpdated += Preference::newInstance()->update(array('s_value' => $selectableParent), array('s_name' => 'selectable_parent_categories')); if ($iUpdated > 0) { if ($error != '') { osc_add_flash_error_message($error . "</p><p>" . _m('General settings have been updated'), 'admin'); } else { osc_add_flash_ok_message(_m('General settings have been updated'), 'admin'); } } else { if ($error != '') { osc_add_flash_error_message($error, 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings'); break; case 'check_updates': osc_admin_toolbar_update_themes(true); osc_admin_toolbar_update_plugins(true); osc_add_flash_ok_message(_m('Last check') . ': ' . date("Y-m-d H:i"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings'); break; case 'latestsearches': //calling the comments settings view $this->doView('settings/searches.php'); break; case 'latestsearches_post': // updating comment if (Params::getParam('save_latest_searches') == 'on') { Preference::newInstance()->update(array('s_value' => 1), array('s_name' => 'save_latest_searches')); } else { Preference::newInstance()->update(array('s_value' => 0), array('s_name' => 'save_latest_searches')); } if (Params::getParam('customPurge') == '') { osc_add_flash_error_message(_m('Custom number could not be left empty'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=latestsearches'); } else { Preference::newInstance()->update(array('s_value' => Params::getParam('customPurge')), array('s_name' => 'purge_latest_searches')); osc_add_flash_ok_message(_m('Last search settings have been updated'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=latestsearches'); } break; default: // calling the view $aLanguages = OSCLocale::newInstance()->listAllEnabled(); $aCurrencies = Currency::newInstance()->listAll(); $this->_exportVariableToView('aLanguages', $aLanguages); $this->_exportVariableToView('aCurrencies', $aCurrencies); $this->doView('settings/index.php'); break; } }
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() { parent::doModel(); //specific things for this class switch ($this->action) { case 'add': $this->doView("appearance/add.php"); break; case 'add_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=appearance'); } osc_csrf_check(); $filePackage = Params::getFiles('package'); if (isset($filePackage['size']) && $filePackage['size'] != 0) { $path = osc_themes_path(); (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path)); } else { $status = 3; } switch ($status) { case 0: $msg = _m('The theme folder is not writable'); osc_add_flash_error_message($msg, 'admin'); break; case 1: $msg = _m('The theme has been installed correctly'); osc_add_flash_ok_message($msg, 'admin'); break; case 2: $msg = _m('The zip file is not valid'); osc_add_flash_error_message($msg, 'admin'); break; case 3: $msg = _m('No file was uploaded'); osc_add_flash_error_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=add"); break; case -1: default: $msg = _m('There was a problem adding the theme'); osc_add_flash_error_message($msg, 'admin'); break; } $this->redirectTo(osc_admin_base_url(true) . "?page=appearance"); break; case 'delete': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=appearance'); } osc_csrf_check(); $theme = Params::getParam('webtheme'); if ($theme != '') { if ($theme != osc_current_web_theme()) { if (osc_deleteDir(osc_content_path() . "themes/" . $theme . "/")) { osc_add_flash_ok_message(_m("Theme removed successfully"), "admin"); } else { osc_add_flash_error_message(_m("There was a problem removing the theme"), "admin"); } } else { osc_add_flash_error_message(_m("Current theme can not be deleted"), "admin"); } } else { osc_add_flash_error_message(_m("No theme selected"), "admin"); } $this->redirectTo(osc_admin_base_url(true) . "?page=appearance"); break; /* widgets */ /* widgets */ case 'widgets': $info = WebThemes::newInstance()->loadThemeInfo(osc_theme()); $this->_exportVariableToView("info", $info); $this->doView('appearance/widgets.php'); break; case 'add_widget': $this->doView('appearance/add_widget.php'); break; case 'edit_widget': $id = Params::getParam('id'); $widget = Widget::newInstance()->findByPrimaryKey($id); $this->_exportVariableToView("widget", $widget); $this->doView('appearance/add_widget.php'); break; case 'delete_widget': osc_csrf_check(); Widget::newInstance()->delete(array('pk_i_id' => Params::getParam('id'))); osc_add_flash_ok_message(_m('Widget removed correctly'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); break; case 'edit_widget_post': osc_csrf_check(); if (!osc_validate_text(Params::getParam("description"))) { osc_add_flash_error_message(_m('Description field is required'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); } $res = Widget::newInstance()->update(array('s_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)), array('pk_i_id' => Params::getParam('id'))); if ($res) { osc_add_flash_ok_message(_m('Widget updated correctly'), 'admin'); } else { osc_add_flash_ok_message(_m('Widget cannot be updated correctly'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); break; case 'add_widget_post': osc_csrf_check(); if (!osc_validate_text(Params::getParam("description"))) { osc_add_flash_error_message(_m('Description field is required'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); } Widget::newInstance()->insert(array('s_location' => Params::getParam('location'), 'e_kind' => 'html', 's_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false))); osc_add_flash_ok_message(_m('Widget added correctly'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets"); break; /* /widget */ /* /widget */ case 'activate': osc_csrf_check(); Preference::newInstance()->update(array('s_value' => Params::getParam('theme')), array('s_section' => 'osclass', 's_name' => 'theme')); osc_add_flash_ok_message(_m('Theme activated correctly'), 'admin'); osc_run_hook("theme_activate", Params::getParam('theme')); $this->redirectTo(osc_admin_base_url(true) . "?page=appearance"); break; case 'render': $this->_exportVariableToView('file', osc_base_path() . Params::getParam("file")); $this->doView('appearance/view.php'); break; default: // $marketError = Params::getParam('marketError'); // $slug = Params::getParam('slug'); // if($marketError!='') { // if($marketError == '0') { // no error installed ok // $help = '<br/><br/><b>' . __('You only need to activate or preview the theme').'</b>'; // osc_add_flash_ok_message( __('Everything was OK!') . ' ( ' . $slug .' ) ' . $help, 'admin'); // } else { // osc_add_flash_error_message( __('Error occurred') . ' ( ' . $slug .' ) ', 'admin'); // } // } // force the recount of themes that need to be updated if (Params::getParam('checkUpdated') != '') { osc_admin_toolbar_update_themes(true); } $themes = WebThemes::newInstance()->getListThemes(); //preparing variables for the view $this->_exportVariableToView("themes", $themes); $this->doView('appearance/index.php'); break; } }
function osc_downloadFile($sourceFile, $downloadedFile) { if (testCurl()) { @set_time_limit(0); $fp = @fopen(osc_content_path() . 'downloads/' . $downloadedFile, 'w+'); if ($fp) { $ch = curl_init($sourceFile); @curl_setopt($ch, CURLOPT_TIMEOUT, 50); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] . ' Osclass (v.' . osc_version() . ')'); curl_setopt($ch, CURLOPT_FILE, $fp); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_REFERER, osc_base_url()); curl_exec($ch); curl_close($ch); fclose($fp); return true; } else { return false; } } else { if (testFsockopen()) { // test curl/fsockopen $downloadedFile = osc_content_path() . 'downloads/' . $downloadedFile; download_fsockopen($sourceFile, $downloadedFile); return true; } } return false; }
function doModel() { parent::doModel(); switch ($this->action) { case 'import': // calling import view $this->doView('tools/import.php'); break; case 'import_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import'); } // calling $sql = Params::getFiles('sql'); if (isset($sql['size']) && $sql['size'] != 0) { $content_file = file_get_contents($sql['tmp_name']); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); if ($comm->importSQL($content_file)) { osc_add_flash_ok_message(_m('Import complete'), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem importing data to the database'), 'admin'); } } else { osc_add_flash_warning_message(_m('No file was uploaded'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import'); break; case 'images': // calling images view $this->doView('tools/images.php'); break; case 'images_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images'); } $preferences = Preference::newInstance()->toArray(); $wat = new Watermark(); $aResources = ItemResource::newInstance()->getAllResources(); foreach ($aResources as $resource) { osc_run_hook('regenerate_image', $resource); $path = osc_content_path() . 'uploads/'; // comprobar que no haya original $img_original = $path . $resource['pk_i_id'] . "_original*"; $aImages = glob($img_original); // there is original image if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_normal = $path . $resource['pk_i_id'] . ".*"; $aImages = glob($img_normal); if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_thumbnail = $path . $resource['pk_i_id'] . "_thumbnail*"; $aImages = glob($img_thumbnail); $image_tmp = $aImages[0]; } } // extension preg_match('/\\.(.*)$/', $image_tmp, $matches); if (isset($matches[1])) { $extension = $matches[1]; // Create normal size $path_normal = $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '.jpg'; $size = explode('x', osc_normal_dimensions()); ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1])->saveToFile($path); if (osc_is_watermark_text()) { $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg'); } elseif (osc_is_watermark_image()) { $wat->doWatermarkImage($path, 'image/jpeg'); } // Create preview $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_preview.jpg'; $size = explode('x', osc_preview_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // Create thumbnail $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_thumbnail.jpg'; $size = explode('x', osc_thumbnail_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // update resource info ItemResource::newInstance()->update(array('s_path' => 'oc-content/uploads/', 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => 'image/jpeg'), array('pk_i_id' => $resource['pk_i_id'])); osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id'])); // si extension es direfente a jpg, eliminar las imagenes con $extension si hay if ($extension != 'jpg') { $files_to_remove = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "*" . $extension; $fs = glob($files_to_remove); if (is_array($fs)) { array_map("unlink", $fs); } } // .... } else { // no es imagen o imagen sin extesión } } osc_add_flash_ok_message(_m('Re-generation complete'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images'); break; case 'category': $this->doView('tools/category.php'); break; case 'category_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=category'); } osc_update_cat_stats(); osc_add_flash_ok_message(_m("Recount category stats has been successful"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=category'); break; case 'locations': $this->doView('tools/locations.php'); break; case 'locations_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=locations'); } $workToDo = LocationsTmp::newInstance()->count(); if ($workToDo > 0) { $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=locations'); break; } // we need populate location tmp table $aCountry = Country::newInstance()->listAll(); foreach ($aCountry as $country) { $aRegionsCountry = Region::newInstance()->getByCountry($country['pk_c_code']); LocationsTmp::newInstance()->insert(array('id_location' => $country['pk_c_code'], 'e_type' => 'COUNTRY')); foreach ($aRegionsCountry as $region) { $aCitiesRegion = City::newInstance()->getByRegion($region['pk_i_id']); LocationsTmp::newInstance()->insert(array('id_location' => $region['pk_i_id'], 'e_type' => 'REGION')); foreach ($aCitiesRegion as $city) { LocationsTmp::newInstance()->insert(array('id_location' => $city['pk_i_id'], 'e_type' => 'CITY')); } unset($aCitiesRegion); } unset($aRegionsCountry); } unset($aCountry); $workToDo = LocationsTmp::newInstance()->count(); Preference::newInstance()->replace('location_todo', $workToDo); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=locations'); break; case 'upgrade': $this->doView('tools/upgrade.php'); break; case 'backup': $this->doView('tools/backup.php'); break; case 'backup-sql': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); } //databasse dump... if (Params::getParam('bck_dir') != '') { $path = trim(Params::getParam('bck_dir')); if (substr($path, -1, 1) != "/") { $path .= '/'; } } else { $path = osc_base_path(); } $filename = 'OSClass_mysqlbackup.' . date('YmdHis') . '.sql'; switch (osc_dbdump($path, $filename)) { case -1: $msg = _m('Path is empty'); osc_add_flash_error_message($msg, 'admin'); break; case -2: $msg = sprintf(_m('Could not connect with the database. Error: %s'), mysql_error()); osc_add_flash_error_message($msg, 'admin'); break; case -3: $msg = _m('There are no tables to back up'); osc_add_flash_error_message($msg, 'admin'); break; case -4: $msg = _m('The folder is not writable'); osc_add_flash_error_message($msg, 'admin'); break; default: $msg = _m('Backup completed successfully'); osc_add_flash_ok_message($msg, 'admin'); break; } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup-sql_file': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); } //databasse dump... $filename = 'OSClass_mysqlbackup.' . date('YmdHis') . '.sql'; $path = sys_get_temp_dir() . "/"; switch (osc_dbdump($path, $filename)) { case -1: $msg = _m('Path is empty'); osc_add_flash_error_message($msg, 'admin'); break; case -2: $msg = sprintf(_m('Could not connect with the database. Error: %s'), mysql_error()); osc_add_flash_error_message($msg, 'admin'); break; case -3: $msg = sprintf(_m('Could not select the database. Error: %s'), mysql_error()); osc_add_flash_error_message($msg, 'admin'); break; case -4: $msg = _m('There are no tables to back up'); osc_add_flash_error_message($msg, 'admin'); break; case -5: $msg = _m('The folder is not writable'); osc_add_flash_error_message($msg, 'admin'); break; default: $msg = _m('Backup completed successfully'); osc_add_flash_ok_message($msg, 'admin'); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($filename)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($path . $filename)); flush(); readfile($path . $filename); exit; break; } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup-zip_file': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); } $filename = "OSClass_backup." . date('YmdHis') . ".zip"; $path = sys_get_temp_dir() . "/"; if (osc_zip_folder(osc_base_path(), $path . $filename)) { $msg = _m('Archived successfully!'); osc_add_flash_ok_message($msg, 'admin'); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($filename)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($path . $filename)); flush(); readfile($path . $filename); exit; } else { $msg = _m('Error, the zip file was not created in the specified directory'); osc_add_flash_error_message($msg, 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup-zip': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); } //zip of the code just to back it up if (Params::getParam('bck_dir') != '') { $archive_name = trim(Params::getParam('bck_dir')); if (substr(trim($archive_name), -1, 1) != "/") { $archive_name .= '/'; } $archive_name = Params::getParam('bck_dir') . '/OSClass_backup.' . date('YmdHis') . '.zip'; } else { $archive_name = osc_base_path() . "OSClass_backup." . date('YmdHis') . ".zip"; } $archive_folder = osc_base_path(); if (osc_zip_folder($archive_folder, $archive_name)) { $msg = _m('Archived successfully!'); osc_add_flash_ok_message($msg, 'admin'); } else { $msg = _m('Error, the zip file was not created in the specified directory'); osc_add_flash_error_message($msg, 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup_post': $this->doView('tools/backup.php'); break; case 'maintenance': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin'); $this->doView('tools/maintenance.php'); break; } $mode = Params::getParam('mode'); if ($mode == 'on') { $maintenance_file = osc_base_path() . '.maintenance'; $fileHandler = @fopen($maintenance_file, 'w'); if ($fileHandler) { osc_add_flash_ok_message(_m('Maintenance mode is ON'), 'admin'); } else { osc_add_flash_error_message(_m('There was an error creating the .maintenance file, please create it manually at the root folder'), 'admin'); } fclose($fileHandler); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance'); } else { if ($mode == 'off') { $deleted = @unlink(osc_base_path() . '.maintenance'); if ($deleted) { osc_add_flash_ok_message(_m('Maintenance mode is OFF'), 'admin'); } else { osc_add_flash_error_message(_m('There was an error removing the .maintenance file, please remove it manually from the root folder'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance'); } } $this->doView('tools/maintenance.php'); break; default: } }
function osc_downloadFile($sourceFile, $downloadedFile) { if (testCurl()) { @set_time_limit(0); $fp = @fopen(osc_content_path() . 'downloads/' . $downloadedFile, 'w+'); if ($fp) { $ch = curl_init($sourceFile); @curl_setopt($ch, CURLOPT_TIMEOUT, 50); curl_setopt($ch, CURLOPT_FILE, $fp); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); curl_close($ch); fclose($fp); return true; } else { return false; } } else { if (testFsockopen()) { // test curl/fsockopen $downloadedFile = osc_content_path() . 'downloads/' . $downloadedFile; download_fsockopen($sourceFile, $downloadedFile); return true; } } }
function fn_email_item_inquiry($aItem) { $id = $aItem['id']; $yourEmail = $aItem['yourEmail']; $yourName = $aItem['yourName']; $phoneNumber = $aItem['phoneNumber']; $message = $aItem['message']; $path = NULL; $item = Item::newInstance()->findByPrimaryKey($id); View::newInstance()->_exportVariableToView('item', $item); $mPages = new Page(); $aPage = $mPages->findByInternalName('email_item_inquiry'); $locale = osc_current_user_locale(); $content = array(); if (isset($aPage['locale'][$locale]['s_title'])) { $content = $aPage['locale'][$locale]; } else { $content = current($aPage['locale']); } $item_url = osc_item_url(); $item_url = '<a href="' . $item_url . '" >' . $item_url . '</a>'; $words = array(); $words[] = array('{CONTACT_NAME}', '{USER_NAME}', '{USER_EMAIL}', '{USER_PHONE}', '{WEB_URL}', '{ITEM_TITLE}', '{ITEM_URL}', '{COMMENT}'); $words[] = array($item['s_contact_name'], $yourName, $yourEmail, $phoneNumber, '<a href="' . osc_base_url() . '" >' . osc_base_url() . '</a>', $item['s_title'], $item_url, $message); $title = osc_mailBeauty(osc_apply_filter('email_title', osc_apply_filter('email_item_inquiry_title', $content['s_title'])), $words); $body = osc_mailBeauty(osc_apply_filter('email_description', osc_apply_filter('email_item_inquiry_description', $content['s_text'])), $words); $from = osc_contact_email(); $from_name = osc_page_title(); $add_bbc = ''; if (osc_notify_contact_item()) { $add_bbc = osc_contact_email(); } $emailParams = array('add_bcc' => $add_bbc, 'from' => $from, 'from_name' => $from_name, 'subject' => $title, 'to' => $item['s_contact_email'], 'to_name' => $item['s_contact_name'], 'body' => $body, 'alt_body' => $body, 'reply_to' => $yourEmail); if (osc_item_attachment()) { $attachment = Params::getFiles('attachment'); $resourceName = $attachment['name']; $tmpName = $attachment['tmp_name']; $resourceType = $attachment['type']; $path = osc_content_path() . 'uploads/' . time() . '_' . $resourceName; if (!is_writable(osc_content_path() . 'uploads/')) { osc_add_flash_error_message(_m('There has been some errors sending the message')); //$this->redirectTo( osc_base_url() ); } if (!move_uploaded_file($tmpName, $path)) { unset($path); } } if (isset($path)) { $emailParams['attachment'] = $path; } osc_sendMail($emailParams); @unlink($path); }
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(); }
case 'db-backup': osc_dbdump(); break; case 'zip-osclass': $archive_name = ABS_PATH . "OSClass_backup." . date('YmdHis') . ".zip"; $archive_folder = ABS_PATH; if (osc_zip_folder($archive_folder, $archive_name)) { $message = __('Archiving is sucessful!'); } else { $message = __('Error, can\'t create a zip file!'); } break; case 'unzip-file': if (Params::getParam('file') != '') { @mkdir(ABS_PATH . 'oc-temp', 0777); $res = osc_unzip_file(osc_content_path() . 'downloads/' . Params::getParam('file'), ABS_PATH . 'oc-temp/'); if ($res == 1) { $message = __('OK'); } else { $message = __('Unzip failed'); } } else { $message = __('Filename incorrect'); } break; case '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); $message = ""; foreach ($lines as $line_num => $r_file) { $unlink = @unlink(ABS_PATH . $r_file);
function doModel() { //specific things for this class switch ($this->action) { case 'bulk_actions': break; case 'regions': //Return regions given a countryId $regions = Region::newInstance()->findByCountry(Params::getParam("countryId")); echo json_encode($regions); break; case 'cities': //Returns cities given a regionId $cities = City::newInstance()->findByRegion(Params::getParam("regionId")); echo json_encode($cities); break; case 'location': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term")); foreach ($cities as $k => $city) { $cities[$k]['label'] = $city['label'] . " (" . $city['region'] . ")"; } echo json_encode($cities); break; case 'location_countries': // This is the autocomplete AJAX $countries = Country::newInstance()->ajax(Params::getParam("term")); echo json_encode($countries); break; case 'location_regions': // This is the autocomplete AJAX $regions = Region::newInstance()->ajax(Params::getParam("term"), Params::getParam("country")); echo json_encode($regions); break; case 'location_cities': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term"), Params::getParam("region")); echo json_encode($cities); break; case 'delete_image': // Delete images via AJAX $ajax_photo = Params::getParam('ajax_photo'); $id = Params::getParam('id'); $item = Params::getParam('item'); $code = Params::getParam('code'); $secret = Params::getParam('secret'); $json = array(); if ($ajax_photo != '') { $files = Session::newInstance()->_get('ajax_files'); $success = false; foreach ($files as $uuid => $file) { if ($file == $ajax_photo) { $filename = $files[$uuid]; unset($files[$uuid]); Session::newInstance()->_set('ajax_files', $files); $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename); break; } } echo json_encode(array('success' => $success, 'msg' => $success ? _m('The selected photo has been successfully deleted') : _m("The selected photo couldn't be deleted"))); return false; } if (Session::newInstance()->_get('userId') != '') { $userId = Session::newInstance()->_get('userId'); $user = User::newInstance()->findByPrimaryKey($userId); } else { $userId = null; $user = null; } // Check for required fields if (!(is_numeric($id) && is_numeric($item) && preg_match('/^([a-z0-9]+)$/i', $code))) { $json['success'] = false; $json['msg'] = _m("The selected photo couldn't be deleted, the url doesn't exist"); echo json_encode($json); return false; } $aItem = Item::newInstance()->findByPrimaryKey($item); // Check if the item exists if (count($aItem) == 0) { $json['success'] = false; $json['msg'] = _m("The listing doesn't exist"); echo json_encode($json); return false; } if (!osc_is_admin_user_logged_in()) { // Check if the item belong to the user if ($userId != null && $userId != $aItem['fk_i_user_id']) { $json['success'] = false; $json['msg'] = _m("The listing doesn't belong to you"); echo json_encode($json); return false; } // Check if the secret passphrase match with the item if ($userId == null && $aItem['fk_i_user_id'] == null && $secret != $aItem['s_secret']) { $json['success'] = false; $json['msg'] = _m("The listing doesn't belong to you"); echo json_encode($json); return false; } } // Does id & code combination exist? $result = ItemResource::newInstance()->existResource($id, $code); if ($result > 0) { $resource = ItemResource::newInstance()->findByPrimaryKey($id); if ($resource['fk_i_item_id'] == $item) { // Delete: file, db table entry if (defined(OC_ADMIN)) { osc_deleteResource($id, true); Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'admin', osc_logged_admin_id()); } else { osc_deleteResource($id, false); Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'user', osc_logged_user_id()); } ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $item, 's_name' => $code)); $json['msg'] = _m('The selected photo has been successfully deleted'); $json['success'] = 'true'; } else { $json['msg'] = _m("The selected photo does not belong to you"); $json['success'] = 'false'; } } else { $json['msg'] = _m("The selected photo couldn't be deleted"); $json['success'] = 'false'; } echo json_encode($json); return true; break; case 'alerts': // Allow to register to an alert given (not sure it's used on admin) $encoded_alert = Params::getParam("alert"); $alert = osc_decrypt_alert(base64_decode($encoded_alert)); // check alert integrity / signature $stringToSign = osc_get_alert_public_key() . $encoded_alert; $signature = hex2b64(hmacsha1(osc_get_alert_private_key(), $stringToSign)); $server_signature = Session::newInstance()->_get('alert_signature'); if ($server_signature != $signature) { echo '-2'; return false; } $email = Params::getParam("email"); $userid = Params::getParam("userid"); if (osc_is_web_user_logged_in()) { $userid = osc_logged_user_id(); $user = User::newInstance()->findByPrimaryKey($userid); $email = $user['s_email']; } if ($alert != '' && $email != '') { if (osc_validate_email($email)) { $secret = osc_genRandomPassword(); if ($alertID = Alerts::newInstance()->createAlert($userid, $email, $alert, $secret)) { if ((int) $userid > 0) { $user = User::newInstance()->findByPrimaryKey($userid); if ($user['b_active'] == 1 && $user['b_enabled'] == 1) { Alerts::newInstance()->activate($alertID); echo '1'; return true; } else { echo '-1'; return false; } } else { $aAlert = Alerts::newInstance()->findByPrimaryKey($alertID); osc_run_hook('hook_email_alert_validation', $aAlert, $email, $secret); } echo "1"; } else { echo "0"; } return true; } else { echo '-1'; return false; } } echo '0'; return false; break; case 'runhook': // run hooks $hook = Params::getParam('hook'); if ($hook == '') { echo json_encode(array('error' => 'hook parameter not defined')); break; } switch ($hook) { case 'item_form': osc_run_hook('item_form', Params::getParam('catId')); break; case 'item_edit': $catId = Params::getParam("catId"); $itemId = Params::getParam("itemId"); osc_run_hook("item_edit", $catId, $itemId); break; default: osc_run_hook('ajax_' . $hook); break; } break; case 'custom': // Execute via AJAX custom file if (Params::existParam('route')) { $routes = Rewrite::newInstance()->getRoutes(); $rid = Params::getParam('route'); $file = '../'; if (isset($routes[$rid]) && isset($routes[$rid]['file'])) { $file = $routes[$rid]['file']; } } else { // DEPRECATED: Disclosed path in URL is deprecated, use routes instead // This will be REMOVED in 3.4 $file = Params::getParam('ajaxfile'); } if ($file == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || stripos($file, '/admin/') !== false) { //If the file is inside an "admin" folder, it should NOT be opened in frontend echo json_encode(array('error' => 'no valid ajaxFile')); break; } if (!file_exists(osc_plugins_path() . $file)) { echo json_encode(array('error' => "ajaxFile doesn't exist")); break; } require_once osc_plugins_path() . $file; break; case 'check_username_availability': $username = osc_sanitize_username(Params::getParam('s_username')); if (!osc_is_username_blacklisted($username)) { $user = User::newInstance()->findByUsername($username); if (isset($user['s_username'])) { echo json_encode(array('exists' => 1, 's_username' => $username)); } else { echo json_encode(array('exists' => 0, 's_username' => $username)); } } else { echo json_encode(array('exists' => 1, 's_username' => $username)); } break; case 'ajax_upload': // Include the uploader class require_once LIB_PATH . "AjaxUploader.php"; $uploader = new AjaxUploader(); $original = pathinfo($uploader->getOriginalName()); $filename = uniqid("qqfile_") . "." . $original['extension']; $result = $uploader->handleUpload(osc_content_path() . 'uploads/temp/' . $filename); $result['uploadName'] = $filename; echo htmlspecialchars(json_encode($result), ENT_NOQUOTES); break; case 'ajax_validate': $id = Params::getParam('id'); if (!is_numeric($id)) { echo json_encode(array('success' => false)); die; } $secret = Params::getParam('secret'); $item = Item::newInstance()->findByPrimaryKey($id); if ($item['s_secret'] != $secret) { echo json_encode(array('success' => false)); die; } $nResources = ItemResource::newInstance()->countResources($id); $result = array('success' => $nResources < osc_max_images_per_item(), 'count' => $nResources); echo json_encode($result); break; case 'delete_ajax_upload': $files = Session::newInstance()->_get('ajax_files'); $success = false; $filename = ''; if (isset($files[Params::getParam('qquuid')]) && $files[Params::getParam('qquuid')] != '') { $filename = $files[Params::getParam('qquuid')]; unset($files[Params::getParam('qquuid')]); Session::newInstance()->_set('ajax_files', $files); $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename); } echo json_encode(array('success' => $success, 'uploadName' => $filename)); break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
function osc_downloadFile($sourceFile, $downloadedFile) { $iErrorReporting = error_reporting(); error_reporting(E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_PARSE); require_once LIB_PATH . 'libcurlemu/libcurlemu.inc.php'; @set_time_limit(0); ini_set('display_errors', true); $fp = @fopen(osc_content_path() . 'downloads/' . $downloadedFile, 'w+'); if ($fp) { $ch = curl_init($sourceFile); @curl_setopt($ch, CURLOPT_TIMEOUT, 50); curl_setopt($ch, CURLOPT_FILE, $fp); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); curl_close($ch); fclose($fp); error_reporting($iErrorReporting); return true; } else { error_reporting($iErrorReporting); return false; } }
function doModel() { switch ($this->action) { case 'import': // calling import view $this->doView('tools/import.php'); break; case 'import_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import'); } // calling $sql = Params::getFiles('sql'); if (isset($sql['size']) && $sql['size'] != 0) { $content_file = file_get_contents($sql['tmp_name']); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); if ($comm->importSQL($content_file)) { osc_add_flash_ok_message(_m('Import complete'), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem importing data to the database'), 'admin'); } } else { osc_add_flash_error_message(_m('No file was uploaded'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import'); break; case 'images': // calling images view $this->doView('tools/images.php'); break; case 'images_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images'); } $preferences = Preference::newInstance()->toArray(); $wat = new Watermark(); $aResources = ItemResource::newInstance()->getAllResources(); foreach ($aResources as $resource) { osc_run_hook('regenerate_image', $resource); $path = osc_content_path() . 'uploads/'; // comprobar que no haya original $img_original = $path . $resource['pk_i_id'] . "_original*"; $aImages = glob($img_original); // there is original image if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_normal = $path . $resource['pk_i_id'] . ".*"; $aImages = glob($img_normal); if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_thumbnail = $path . $resource['pk_i_id'] . "_thumbnail*"; $aImages = glob($img_thumbnail); $image_tmp = $aImages[0]; } } // extension preg_match('/\\.(.*)$/', $image_tmp, $matches); if (isset($matches[1])) { $extension = $matches[1]; // Create normal size $path_normal = $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '.jpg'; $size = explode('x', osc_normal_dimensions()); ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1])->saveToFile($path); if (osc_is_watermark_text()) { $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg'); } elseif (osc_is_watermark_image()) { $wat->doWatermarkImage($path, 'image/jpeg'); } // Create preview $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_preview.jpg'; $size = explode('x', osc_preview_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // Create thumbnail $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_thumbnail.jpg'; $size = explode('x', osc_thumbnail_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // update resource info ItemResource::newInstance()->update(array('s_path' => 'oc-content/uploads/', 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => 'image/jpeg'), array('pk_i_id' => $resource['pk_i_id'])); osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id'])); // si extension es direfente a jpg, eliminar las imagenes con $extension si hay if ($extension != 'jpg') { $files_to_remove = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "*" . $extension; $fs = glob($files_to_remove); if (is_array($fs)) { array_map("unlink", $fs); } } // .... } else { // no es imagen o imagen sin extesión } } osc_add_flash_ok_message(_m('Re-generation complete'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images'); break; case 'upgrade': $this->doView('tools/upgrade.php'); break; case 'backup': $this->doView('tools/backup.php'); break; case 'backup-sql': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); } //databasse dump... if (Params::getParam('bck_dir') != '') { $path = trim(Params::getParam('bck_dir')); if (substr($path, -1, 1) != "/") { $path .= '/'; } } else { $path = osc_base_path(); } $filename = 'OSClass_mysqlbackup.' . date('YmdHis') . '.sql'; switch (osc_dbdump($path, $filename)) { case -1: $msg = _m('Path is empty'); osc_add_flash_error_message($msg, 'admin'); break; case -2: $msg = sprintf(_m('Could not connect with the database. Error: %s'), mysql_error()); osc_add_flash_error_message($msg, 'admin'); break; case -3: $msg = sprintf(_m('Could not select the database. Error: %s'), mysql_error()); osc_add_flash_error_message($msg, 'admin'); break; case -4: $msg = _m('There are no tables to back up'); osc_add_flash_error_message($msg, 'admin'); break; case -5: $msg = _m('The folder is not writable'); osc_add_flash_error_message($msg, 'admin'); break; default: $msg = _m('Backup has been done properly'); osc_add_flash_ok_message($msg, 'admin'); break; } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup-zip': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); } //zip of the code just to back it up if (Params::getParam('bck_dir') != '') { $archive_name = trim(Params::getParam('bck_dir')); if (substr(trim($archive_name), -1, 1) != "/") { $archive_name .= '/'; } $archive_name = Params::getParam('bck_dir') . '/OSClass_backup.' . date('YmdHis') . '.zip'; } else { $archive_name = osc_base_path() . "OSClass_backup." . date('YmdHis') . ".zip"; } $archive_folder = osc_base_path(); if (osc_zip_folder($archive_folder, $archive_name)) { $msg = _m('Archiving successful!'); osc_add_flash_ok_message($msg, 'admin'); } else { $msg = _m('Error, the zip file was not created at the specified directory'); osc_add_flash_error_message($msg, 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup_post': $this->doView('tools/backup.php'); break; case 'maintenance': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin'); $this->doView('tools/maintenance.php'); break; } $mode = Params::getParam('mode'); if ($mode == 'on') { $maintenance_file = ABS_PATH . '.maintenance'; $fileHandler = @fopen($maintenance_file, 'w'); if ($fileHandler) { osc_add_flash_ok_message(_m('Maintenance mode is ON'), 'admin'); } else { osc_add_flash_error_message(_m('There was an error creating .maintenance file, please create it manually at the root folder'), 'admin'); } fclose($fileHandler); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance'); } else { if ($mode == 'off') { $deleted = @unlink(ABS_PATH . '.maintenance'); if ($deleted) { osc_add_flash_ok_message(_m('Maintenance mode is OFF'), 'admin'); } else { osc_add_flash_error_message(_m('There was an error removing .maintenance file, please remove it manually from the root folder'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance'); } } $this->doView('tools/maintenance.php'); break; default: } }
/** * Return an array with all data necessary for do the action (ADD OR EDIT) * @param <type> $is_add * @return array */ public function prepareData( $is_add ) { $aItem = array(); $data = array(); $userId = null; if( $this->is_admin ) { // user $data = User::newInstance()->findByEmail(Params::getParam('contactEmail')); if( isset($data['pk_i_id']) && is_numeric($data['pk_i_id']) ) { $userId = $data['pk_i_id']; } } else { $userId = Session::newInstance()->_get('userId'); if( $userId == '' ) { $userId = NULL; } elseif ($userId != NULL) { $data = User::newInstance()->findByPrimaryKey( $userId ); } } if( $userId != null ) { $aItem['contactName'] = $data['s_name']; $aItem['contactEmail'] = $data['s_email']; Params::setParam('contactName', $data['s_name']); Params::setParam('contactEmail', $data['s_email']); } else { $aItem['contactName'] = Params::getParam('contactName'); $aItem['contactEmail'] = Params::getParam('contactEmail'); } $aItem['userId'] = $userId; if( $is_add ) { // ADD if($this->is_admin) { $active = 'ACTIVE'; } else { if(osc_moderate_items()>0) { // HAS TO VALIDATE if(!osc_is_web_user_logged_in()) { // NO USER IS LOGGED, VALIDATE $active = 'INACTIVE'; } else { // USER IS LOGGED if(osc_logged_user_item_validation()) { //USER IS LOGGED, BUT NO NEED TO VALIDATE $active = 'ACTIVE'; } else { // USER IS LOGGED, NEED TO VALIDATE, CHECK NUMBER OF PREVIOUS ITEMS $user = User::newInstance()->findByPrimaryKey(osc_logged_user_id()); if($user['i_items']<osc_moderate_items()) { $active = 'INACTIVE'; } else { $active = 'ACTIVE'; } } } } else if(osc_moderate_items()==0 ){ if(osc_is_web_user_logged_in() && osc_logged_user_item_validation() ) { $active = 'ACTIVE'; } else { $active = 'INACTIVE'; } } else { $active = 'ACTIVE'; } } $aItem['active'] = $active; } else { // EDIT $aItem['secret'] = Params::getParam('secret'); $aItem['idItem'] = Params::getParam('id'); } // get params $aItem['catId'] = Params::getParam('catId'); $aItem['countryId'] = Params::getParam('countryId'); $aItem['country'] = Params::getParam('country'); $aItem['region'] = Params::getParam('region'); $aItem['regionId'] = Params::getParam('regionId'); $aItem['city'] = Params::getParam('city'); $aItem['cityId'] = Params::getParam('cityId'); $aItem['price'] = (Params::getParam('price') != '') ? Params::getParam('price') : null; $aItem['cityArea'] = Params::getParam('cityArea'); $aItem['address'] = Params::getParam('address'); $aItem['currency'] = Params::getParam('currency'); $aItem['showEmail'] = (Params::getParam('showEmail') != '') ? 1 : 0; $aItem['title'] = Params::getParam('title'); $aItem['description'] = Params::getParam('description'); $aItem['photos'] = Params::getFiles('photos'); $ajax_photos = Params::getParam('ajax_photos'); $aItem['s_ip'] = get_ip(); $aItem['d_coord_lat'] = (Params::getParam('d_coord_lat') != '') ? Params::getParam('d_coord_lat') : null; $aItem['d_coord_long'] = (Params::getParam('d_coord_long') != '') ? Params::getParam('d_coord_long') : null; $aItem['s_zip'] = (Params::getParam('zip') != '') ? Params::getParam('zip') : null; // $ajax_photos is an array of filenames of the photos uploaded by ajax to a temporary folder // fake insert them into the array of the form-uploaded photos if(is_array($ajax_photos)) { foreach($ajax_photos as $photo) { if(file_exists(osc_content_path().'uploads/temp/'.$photo)) { $aItem['photos']['name'][] = $photo; $aItem['photos']['type'][] = 'image/*'; $aItem['photos']['tmp_name'][] = osc_content_path().'uploads/temp/'.$photo; $aItem['photos']['error'][] = UPLOAD_ERR_OK; $aItem['photos']['size'][] = 0; } } } if($is_add || $this->is_admin) { $dt_expiration = Params::getParam('dt_expiration'); if($dt_expiration==-1) { $aItem['dt_expiration'] = ''; } else if($dt_expiration!='' && (preg_match('|^([0-9]+)$|', $dt_expiration, $match) || preg_match('|([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})|', $dt_expiration, $match))) { $aItem['dt_expiration'] = $dt_expiration; } else { $_category = Category::newInstance()->findByPrimaryKey($aItem['catId']); $aItem['dt_expiration'] = $_category['i_expiration_days']; } unset($dt_expiration); } else { $aItem['dt_expiration'] = ''; }; // check params $country = Country::newInstance()->findByCode($aItem['countryId']); if( count($country) > 0 ) { $countryId = $country['pk_c_code']; $countryName = $country['s_name']; } else { $countryId = null; $countryName = $aItem['country']; } $aItem['countryId'] = $countryId; $aItem['countryName'] = $countryName; if( $aItem['regionId'] != '' ) { if( intval($aItem['regionId']) ) { $region = Region::newInstance()->findByPrimaryKey($aItem['regionId']); if( count($region) > 0 ) { $regionId = $region['pk_i_id']; $regionName = $region['s_name']; } } } else { $regionId = null; $regionName = $aItem['region']; if( $aItem['countryId'] != '' ) { $auxRegion = Region::newInstance()->findByName($aItem['region'], $aItem['countryId'] ); if($auxRegion){ $regionId = $auxRegion['pk_i_id']; $regionName = $auxRegion['s_name']; } } } $aItem['regionId'] = $regionId; $aItem['regionName'] = $regionName; if( $aItem['cityId'] != '' ) { if( intval($aItem['cityId']) ) { $city = City::newInstance()->findByPrimaryKey($aItem['cityId']); if( count($city) > 0 ) { $cityId = $city['pk_i_id']; $cityName = $city['s_name']; } } } else { $cityId = null; $cityName = $aItem['city']; if( $aItem['countryId'] != '' ) { $auxCity = City::newInstance()->findByName($aItem['city'], $aItem['regionId'] ); if($auxCity){ $cityId = $auxCity['pk_i_id']; $cityName = $auxCity['s_name']; } } } $aItem['cityId'] = $cityId; $aItem['cityName'] = $cityName; if( $aItem['cityArea'] == '' ) { $aItem['cityArea'] = null; } if( $aItem['address'] == '' ) { $aItem['address'] = null; } if( !is_null($aItem['price']) ) { $price = str_replace(osc_locale_thousands_sep(), '', trim($aItem['price'])); $price = str_replace(osc_locale_dec_point(), '.', $price); $aItem['price'] = $price*1000000; //$aItem['price'] = (float) $aItem['price']; } if( $aItem['catId'] == ''){ $aItem['catId'] = 0; } if( $aItem['currency'] == '' ) { $aItem['currency'] = null; } $this->data = $aItem; }
function doModel() { switch ($this->action) { case 'import': // calling import view $this->doView('tools/import.php'); break; case 'import_post': // calling $sql = Params::getFiles('sql'); //dev.conquer: if the file es too big, we can have problems with the upload or with memory $content_file = file_get_contents($sql['tmp_name']); $conn = getConnection(); if ($conn->osc_dbImportSQL($content_file)) { osc_add_flash_message(_m('Import complete'), 'admin'); } else { osc_add_flash_message(_m('There was a problem importing data to the database'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import'); break; case 'images': // calling images view $this->doView('tools/images.php'); break; case 'images_post': $preferences = Preference::newInstance()->toArray(); $path = osc_content_path() . 'uploads/'; $dir = opendir($path); while ($file = readdir($dir)) { if (preg_match('|([0-9]+)_thumbnail\\.png|i', $file, $matches)) { $orig_file = str_replace('_thumbnail.', '_original.', $file); $tmpName = osc_content_path() . 'uploads/' . $orig_file; if (!file_exists($orig_file)) { copy(str_replace('_original.', '.', $tmpName), $tmpName); } // Create thumbnail $thumbnailPath = osc_content_path() . 'uploads/' . $file; $size = explode('x', osc_thumbnail_dimensions()); ImageResizer::fromFile($tmpName)->resizeTo($size[0], $size[1])->saveToFile($thumbnailPath); // Create preview $thumbnailPath = osc_content_path() . 'uploads/' . str_replace('_thumbnail.', '_preview.', $file); $size = explode('x', osc_preview_dimensions()); ImageResizer::fromFile($tmpName)->resizeTo($size[0], $size[1])->saveToFile($thumbnailPath); // Create normal size $thumbnailPath = osc_content_path() . 'uploads/' . str_replace('_thumbnail.', '.', $file); $size = explode('x', osc_normal_dimensions()); ImageResizer::fromFile($tmpName)->resizeTo($size[0], $size[1])->saveToFile($thumbnailPath); if (!osc_keep_original_image()) { @unlink($tmpName); } } } closedir($dir); osc_add_flash_message(_m('Re-generation complete'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images'); break; case 'upgrade': $this->doView('tools/upgrade.php'); break; case 'backup': $this->doView('tools/backup.php'); break; case 'backup-sql': //databasse dump... if (Params::getParam('bck_dir') != '') { $path = trim(Params::getParam('bck_dir')); if (substr($path, -1, 1) != "/") { $path .= '/'; } } else { $path = osc_base_path(); } $filename = 'OSClass_mysqlbackup.' . date('YmdHis') . '.sql'; switch (osc_dbdump($path, $filename)) { case -1: $msg = _m('Path is empty'); break; case -2: $msg = _m('Could not connect with the database') . '. Error: ' . mysql_error(); break; case -3: $msg = _m('Could not select the database') . '. Error: ' . mysql_error(); break; case -4: $msg = _m('There are no tables to back up'); break; case -5: $msg = _m('The folder is not writable'); break; default: $msg = _m('Backup has been done properly'); break; } osc_add_flash_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup-zip': //zip of the code just to back it up if (Params::getParam('bck_dir') != '') { $archive_name = trim(Params::getParam('bck_dir')); if (substr(trim($archive_name), -1, 1) != "/") { $archive_name .= '/'; } $archive_name = Params::getParam('bck_dir') . '/OSClass_backup.' . date('YmdHis') . '.zip'; } else { $archive_name = osc_base_path() . "OSClass_backup." . date('YmdHis') . ".zip"; } $archive_folder = osc_base_path(); if (osc_zip_folder($archive_folder, $archive_name)) { $msg = _m('Archiving successful!'); } else { $msg = _m('Error, the zip file was not created at the specified directory'); } osc_add_flash_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup'); break; case 'backup_post': $this->doView('tools/backup.php'); break; default: } }