Create a plugin to remove ad/listing spam. currently the item list only can show 100 ad max. create a plugin so it can remove as many ad as we want???
How to delete more than 100 listing on the ‘manage listing’ page on the admin page?
SOLUTION: (NOT COMPLETED YET) need to learn the code in /oc-admin/items.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
... case 'delete_all': $id = Params::getParam('id'); $success = false; if($id) { $numSuccess = 0; foreach($id as $i) { if ($i) { $item = $this->itemManager->findByPrimaryKey($i); $success = $mItems->delete($item['s_secret'], $item['pk_i_id']); if($success) { $numSuccess++; } } } osc_add_flash_ok_message( sprintf(_mn('%d listing has been deleted', '%d listings have been deleted', $numSuccess), $numSuccess), 'admin'); } ... |
but Params::getParam(‘id’) only can see the ‘id’ on the checked values on the manage list. even though the max listing on the list only 100. so how to delete more than that??? learn again this line:
|
1 |
$mItems->delete($item['s_secret'], $item['pk_i_id']); |
OK. now how to get the list all of the item id??? or from an item id to another item id??? HOMEWORK!!!
OK. I can do this without use the admin listing page. but instead of creating a new plugin (it’d need more work), I use another plugin (use the functions, model, etc). its real esatet plugin. First of all, in /plugins/realestate_attributes/ModelRealEstate.php file, I added two functions. The first to call the item table and the second to populate the specific item data based on our criteria.
|
1 2 3 4 5 6 7 8 9 10 |
public function getTable_Item() { return DB_TABLE_PREFIX.'t_item'; } public function getSpecificItem() { $result = $this->dao->query( sprintf("SELECT pk_i_id FROM %s WHERE pk_i_id < 19812", $this->getTable_Item()) ) ; return $result->result() ; } |
Then in /plugins/realestate_attributes/conf.php file, we call those function at the beginning.
|
1 2 3 4 5 6 |
$specific_item = ModelRealEstate::newInstance()->getSpecificItem() ; foreach ($specific_item as $s) { $mItems = new ItemActions( true ); $item = Item::newInstance()->findByPrimaryKey($s['pk_i_id']); $mItems->delete($item['s_secret'], $item['pk_i_id']); } |
We can run it on our browser with url http://localhost/…/oc-admin/index.php?page=plugins&action=renderplugin&file=realestate_attributes/conf.php. But becareful to use this script. If we have many records that need to be deleted, it’d take many time and computer/server resource. sometimes I got a message: “Fatal error: Maximum execution time of 30 seconds exceeded in /home/…/oc-includes/osclass/model/Item.php on line 128“. So check your server setting! Do you have more elegant solutions?
How to create multi step posting ad page?
currently multi step can’t move back to the previous step (http://localhost/works/kokopage/index.php?page=item&action=item_add). I have to refresh it. but can use ‘previous’ button?
The Steps (previous and next) on each page are showed up by helping of jquery. the jquery script is reside in /themes/classer/js/FormToWizard.js
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
/* Created by jankoatwarpspeed.com */ (function($) { $.fn.formToWizard = function(options) { options = $.extend({ submitButton: "" }, options); var element = this; var steps = $(element).find("fieldset"); var count = steps.size(); var submmitButtonName = "#" + options.submitButton; $(submmitButtonName).hide(); // 2 $(element).before("<ul id='steps'></ul>"); steps.each(function(i) { $(this).wrap("<div id='step" + i + "'></div>"); $(this).append("<p id='step" + i + "commands'></p>"); // 2 var name = $(this).find("h2").html(); $("#steps").append("<li id='stepDesc" + i + "'>Step " + (i + 1) + "<span>" + name + "</span></li>"); if (i == 0) { createNextButton(i); selectStep(i); } else if (i == count - 1) { $("#step" + i).hide(); createPrevButton(i); createPreviewButton(i); } else { $("#step" + i).hide(); createPrevButton(i); createNextButton(i); } }); function createPrevButton(i) { var stepName = "step" + i; $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Prev' class='prev'> Back</a>"); $("#" + stepName + "Prev").bind("click", function(e) { $("#" + stepName).hide(); $("#step" + (i - 1)).show(); $(submmitButtonName).hide(); selectStep(i - 1); }); } function createNextButton(i) { var stepName = "step" + i; $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Next' class='next'>Next </a>"); $("#" + stepName + "Next").bind("click", function(e) { $("#" + stepName).hide(); $("#step" + (i + 1)).show(); if (i + 2 == count) $(submmitButtonName).show(); selectStep(i + 1); }); } function createPreviewButton(i) { var stepName = "step" + i; $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Next' class='next'>Preview Ad </a>"); $("#" + stepName + "Next").bind("click", function(e) { $("form#item-post").submit(); }); } function selectStep(i) { $("#steps li").removeClass("current"); $("#stepDesc" + i).addClass("current"); } } })(jQuery); |
Then call the script on /themes/classer/item-post.php like this
|
1 2 3 4 5 |
<script type="text/javascript"> $(document).ready(function(){ $("#postingitem").formToWizard({ submitButton: 'SaveAccount' }) }); </script> |
OSCLASS TIPS & TRICKS
1. show warning and error on page -> Put define(‘OSC_DEBUG’, true) ; in config.php
2. show sql query on page -> Put define(‘OSC_DEBUG_DB’, true) ; in config.php
3. Change item url from http://localhost/Projects/motobroker/sedans/auction-1_i60
to http://localhost/Projects/motobroker/victoria/airport-west/sedans/auction-1_i60 (incluided region and city), pls do this (hard code) :
a. edit oc_t_preference table and find ‘rewrite_item_url’. then change from {CATEGORIES}/{ITEM_TITLE}_i{ITEM_ID}
to {ITEM_REGION}/{ITEM_CITY}/{CATEGORIES}/{ITEM_TITLE}_i{ITEM_ID}
NOTE: We can’t just use {ITEM_REGION}/{ITEM_CITY}/{CATEGORIES}/{ITEM_TITLE} . it’d display 404 page. we must add ‘_i{ITEM_ID}’ at the end
b. find and edit function ‘osc_item_url_from_item’ in /oc-includes/osclass/helpers/hDefines.php. add the region part :
$url = str_replace(‘{ITEM_REGION}’, osc_sanitizeString($item[‘s_region’]), $url);
so it’ll be
function osc_item_url_from_item($item, $locale = ”)
{
if ( osc_rewrite_enabled() ) {
$url = osc_get_preference(‘rewrite_item_url’);
if( preg_match(‘|{CATEGORIES}|’, $url) ) {
$sanitized_categories = array();
$cat = Category::newInstance()->hierarchy($item[‘fk_i_category_id’]);
for ($i = (count($cat)); $i > 0; $i–) {
$sanitized_categories[] = $cat[$i – 1][‘s_slug’];
}
$url = str_replace(‘{CATEGORIES}’, implode(“/”, $sanitized_categories), $url);
}
$url = str_replace(‘{ITEM_ID}’, osc_sanitizeString($item[‘pk_i_id’]), $url);
$url = str_replace(‘{ITEM_REGION}’, osc_sanitizeString($item[‘s_region’]), $url);
$url = str_replace(‘{ITEM_CITY}’, osc_sanitizeString($item[‘s_city’]), $url);
$url = str_replace(‘{ITEM_TITLE}’, osc_sanitizeString($item[‘s_title’]), $url);
$url = str_replace(‘?’, ”, $url);
if($locale!=”) {
$path = osc_base_url().$locale.”/”.$url;
} else {
$path = osc_base_url().$url;
}
} else {
$path = osc_item_url_ns($item[‘pk_i_id’], $locale);
}
return $path;
}
4. Get static page url : If we want to get an url of the static/customized page, pls do like this (http://forums.osclass.org/general-help/get-url-of-a-page/):
<?php osc_get_static_page(‘page_name’); ?>
<a href=”<? php echo osc_static_page_url(); ?>”>Page Title</a>
5. How to find out if this the admin page or not?
Pls use: if( OC_ADMIN ) {
5. How to send/flash message?
Pls use like this (before the redirection):
osc_add_flash_ok_message(__(‘Killer form deleted correctly’, ‘jobboard’), ‘admin’); //success/ok message
osc_add_flash_info_message(__(‘Killer form deleted correctly’, ‘jobboard’), ‘admin’); //info/notif message
osc_add_flash_message(__(‘Problems tring to remove killer question form. Try it again.’, ‘jobboard’), ‘admin’);//errro message
osc_add_flash_error_message(__(“Name is required”, ‘jobboard’));//error message
For the redirection, pls use:
osc_redirect_to(osc_admin_render_plugin_url(“jobboard/manage_killer.php”)); //sometime return error/warning
job_js_redirect_to(osc_admin_render_plugin_url(“jobboard/manage_killer.php”)); //sometime return error/warning
header(‘Location: ‘ . osc_admin_render_plugin_url(“jobboard/people.php”)); exit;//usually success
6. How to load the classes in the plugin? especially for loading MVC (model, view and controller) class (no controller here)
pls do like this (in plugin index.php): ref: /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/index.php
define(‘JOBBOARD_PATH’, dirname(__FILE__) . ‘/’);
define(‘JOBBOARD_VIEWS’, JOBBOARD_PATH . ‘views/’);
require_once(JOBBOARD_PATH . ‘model/ModelJB.php’);
require_once(JOBBOARD_PATH . ‘model/ModelKQ.php’);
…
7. Put all actions (hooks) in a class
usually hooks reside in index.php of plugins. but here we can put them in a class and call it like this:
/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/index.php:
define(‘JOBBOARD_PATH’, dirname(__FILE__) . ‘/’);
define(‘JOBBOARD_VIEWS’, JOBBOARD_PATH . ‘views/’);
…
require_once(JOBBOARD_PATH . ‘class/JobboardListingActions.php’);
…
// init classes
…
$jb_listing_actions = new JobboardListingActions();
…
/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/class/JobboardListingActions.php:
class JobboardListingActions
{
public function __construct() {
// add/add-post
osc_add_hook(‘item_form’, array(&$this, ‘jobboard_form’) );
osc_add_hook(‘posted_item’, array(&$this, ‘jobboard_form_post’) );
…
}
function jobboard_form($catID = null) {
…
}
}
Here we must use a reference (&) to return the callback values like this: array(&$this, ‘jobboard_form’) )
8. how to create/display a toolbar menu in admin dashboard?
we can put them in a class and call it like this:
/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/index.php:
define(‘JOBBOARD_PATH’, dirname(__FILE__) . ‘/’);
define(‘JOBBOARD_VIEWS’, JOBBOARD_PATH . ‘views/’);
…
if( OC_ADMIN ) {
…
require_once(JOBBOARD_PATH . ‘class/JobboardAdminMenu.php’);
…
// init oc-admin classes
…
$jb_admin_menu = new JobboardAdminMenu();
…
}
…
/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/class/JobboardAdminMenu.php:
class JobboardAdminMenu
{
public function __construct() {
osc_add_hook(‘admin_menu_init’, array(&$this, ‘init’));
}
/**
* Add new menu entries
*/
public function init() {
osc_add_admin_menu_page(
__(‘Jobboard’, ‘jobboard’),
osc_admin_render_plugin_url(“jobboard/dashboard.php”),
‘jobboard’,
‘moderator’
);
osc_add_admin_submenu_page(
‘jobboard’,
__(‘Dashboard’, ‘jobboard’),
osc_admin_render_plugin_url(“jobboard/dashboard.php”),
‘jobboard_dash’,
‘moderator’
);
osc_add_admin_submenu_page(
‘jobboard’,
__(‘Applicants’, ‘jobboard’),
osc_admin_render_plugin_url(“jobboard/people.php”),
‘jobboard_people’,
‘moderator’
);
// killer questions menu
osc_add_admin_submenu_page(
‘jobboard’,
__(‘Killer Questions’, ‘jobboard’),
osc_admin_render_plugin_url(“jobboard/manage_killer.php”),
‘jobboard_killer’,
‘moderator’
);
osc_add_admin_submenu_page(
‘jobboard’,
__(‘Download resumes’, ‘jobboard’),
osc_admin_render_plugin_url(“jobboard/resume_download.php”),
‘jobboard_resumedownload’,
‘moderator’
);
osc_add_admin_submenu_page(
‘jobboard’,
__(‘Default locations’, ‘jobboard’),
osc_admin_render_plugin_url(“jobboard/admin/settings.php”),
‘jobboard_locations’,
‘moderator’
);
}
Here we use ‘osc_add_admin_menu_page’ to create the toolbar and ‘osc_add_admin_submenu_page’ to create the sub-toolbar
9. We better use ‘Cookie’ to send a value just from a page to another page instead of ‘Session’. in the another page we can use ????? With ‘cookies’ we can set and store how long (day, month or year) the values would last but ‘session’ only for current values (in a day)
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/index.php:
…
if( Params::getParam(‘iDisplayLength’) != ” ) {
Cookie::newInstance()->push(‘applicants_iDisplayLength’, Params::getParam(‘iDisplayLength’));
Cookie::newInstance()->set();
} else {
// set a default value if it’s set in the cookie
if( Cookie::newInstance()->get_value(‘applicants_iDisplayLength’) != ” ) {
Params::setParam(‘iDisplayLength’, Cookie::newInstance()->get_value(‘applicants_iDisplayLength’));
} else {
Params::setParam(‘iDisplayLength’, 10);
}
}
9. Is it better to use ‘osc_get_preference’ and ‘osc_set_preference’??
Its better to use those functions to store/get values for the plugins settings
example:
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/people.php:
$feature = (int) osc_get_preference(‘new_feature_add_applicant’, ‘jobboard_plugin’);
if( $feature === 0 ) {
osc_set_preference(‘new_feature_add_applicant’, 1, ‘jobboard_plugin’);
}
10. For what and why use View::newInstance()->_exportVariableToView(‘items’, $aItems); ??
The code will export/spit out items with some ‘items helper’ function on ‘View’ class that we can use like osc_item_id(), osc_item_category_id(), etc
We can use this code to get the ‘items’ data by primary key without the helpers:
$item = Item::newInstance()->findByPrimaryKey($applicant[‘fk_i_item_id’]);
echo $item[‘s_title’]; –> CAN’T GET $item[‘s_title’]
another variations:
ref:/plugins/mb_auction/ModelMBAuction.php:
View::newInstance()->_exportVariableToView(‘items’, Search::newInstance()->doSearch());
View::newInstance()->_exportVariableToView(“item”, Item::newInstance()->findByPrimaryKey($itemId));
ref:/plugins/mb_auction/themes/default/auction_dashboard_widget.php:
View::newInstance()->_exportVariableToView(‘footer_link’, $f);
10. How to loop search result (can use osc_item_id())
Pls do this:
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/people.php:
$mSearch = new Search();
$mSearch->limit(0, 100);
$aItems = $mSearch->doSearch();
View::newInstance()->_exportVariableToView(‘items’, $aItems);
then we can use the helpers functions like ‘osc_item_id()’
if we want to search something simple and just return the result count, we can do it like this:
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/dashboard.php:
<?php
$mSearch = new Search(true);
$mSearch->addItemConditions(DB_TABLE_PREFIX.’t_item.b_enabled = 1′);
?>
</div>
<b><?php echo $mSearch->count(); ?></b>
‘new Search(true)’ mean we can also search the ‘expired’ item (ref:/oc-includes/osclass/model/Search.php)
‘Search’ class only to search data in the ‘oc_t_item’ table.
or we can also use like this with some search queries (use ‘addItemConditions’):
ref:/kokopage/oc-content/themes/classer/functions.php: (similar query)
View::newInstance()->_exportVariableToView(‘items’, array());//I dont know if its better to empty the ‘items’ first
$mSearch = new Search();
$mSearch->addCategory(osc_item_category_id());
$mSearch->addItemConditions(sprintf(“%st_item.pk_i_id != %s “, DB_TABLE_PREFIX, osc_item_id()));
$mSearch->limit(‘0’, $max_item);
$aItems = $mSearch->doSearch();
$iTotalItems = count($aItems);
if( $iTotalItems > 0 ) {
View::newInstance()->_exportVariableToView(‘items’, $aItems);
return $iTotalItems;
}
unset($mSearch);
return 0;
then in the loop:
<?php while( osc_has_items() ) { ?>
<?php echo osc_item_id(); ?>
<?php } ?>
or we can also do like this (more complex queries):
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/dashboard.php:
$mSearch4 = new Search(true);
$mSearch4->addTable(DB_TABLE_PREFIX.”t_item_stats”);
$mSearch4->addField(“SUM(“.DB_TABLE_PREFIX.”t_item_stats.i_num_views) as i_num_views”);
$mSearch4->addConditions(DB_TABLE_PREFIX.”t_item_stats.fk_i_item_id = “.DB_TABLE_PREFIX.”t_item.pk_i_id”);
$mSearch4->order(‘i_num_views’);
$mSearch4->set_rpp(1);
$mSearch4->addGroupBy(“fk_i_item_id”);
$mostViewedJob = $mSearch4->doSearch();
Without export it to ‘View’ because it only return 1 record, we can get the data without looping like this:
$mostViewedJob[0][‘i_num_views’]
$mostViewedJob[0][‘fk_i_item_id’]
$mostViewedJob[0][‘s_title’]
or even like this (more2 complex query):
ref:/kokopage/oc-content/themes/classer/functions.php: (featured listing):
function featured_listings() {
$category_id=0;
$category_query=””;
if(Params::getParam(‘sCategory’)){
$cats=array();
$cat=Category::newInstance()->findNameByPrimaryKey(Params::getParam(‘sCategory’));
if($cat){
//find in the sub category
$subCategories = Category::newInstance()->toSubTree(Params::getParam(‘sCategory’));
if($subCategories){
foreach($subCategories as $s){
$cats[]=$s[‘pk_i_id’];
}
$category_id=Params::getParam(‘sCategory’).’,’.implode($cats,’,’);
$category_query=”IN (“.$category_id.”)”;
}else{
$category_id=Params::getParam(‘sCategory’);
$category_query=”= “.$category_id;
}
}else{
//category id is not exist
$category_id=-1;
$category_query=”= -1″;
}
}
$max_item=16;
$mSearch = new Search();
$mSearch->addTable(DB_TABLE_PREFIX.”t_item_promoted_ad”);
$mSearch->addConditions(DB_TABLE_PREFIX.”t_item.pk_i_id = “.DB_TABLE_PREFIX.”t_item_promoted_ad.fk_i_item_id”);
if($category_id)
$mSearch->addConditions(DB_TABLE_PREFIX.”t_item.fk_i_category_id “.$category_query);
$mSearch->addConditions(DB_TABLE_PREFIX.”t_item_promoted_ad.i_paid = 1″);
$mSearch->addConditions(DB_TABLE_PREFIX.”t_item_promoted_ad.dt_expiration IS NOT NULL”);
$mSearch->order(DB_TABLE_PREFIX.”t_item.pk_i_id”);
$mSearch->addGroupBy(DB_TABLE_PREFIX.”t_item.pk_i_id”);
$mSearch->limit(‘0’, $max_item);
$aItems = $mSearch->doSearch();
$iTotalItems = count($aItems);
if( $iTotalItems > 0 ) {
View::newInstance()->_exportVariableToView(‘items’, $aItems);
return $iTotalItems;
}
unset($mSearch);
return 0;
}
11. How to find ‘Total View’?
pls use ‘ItemStats’ static class like this:
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/dashboard.php:
<?php echo ItemStats::newInstance()->getAllViews(); ?>
12. How to include another files outside our plugin?
pls use like this: (to include core ‘oc-load.php’)
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/download.php:
define(‘ABS_PATH’, dirname(dirname(dirname(dirname($_SERVER[‘SCRIPT_FILENAME’])))) . ‘/’);
require_once(ABS_PATH . ‘oc-load.php’);
or if we know the file we want to include in ‘/oc-includes’ directory, just use ‘osc_lib_path()’ like this:
require_once(osc_lib_path() . ‘osclass/helpers/hErrors.php’);
13. How to make ‘download/upload’ pdf file?
pls see in : /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/download.php
also use some ‘header’ function like : header(‘Content-Disposition: attachment; filename=’ . $pdf_name);
13. How to upload file (ex: CV):
pls see in : /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/ReciveCv.php
13. How to resume Download?
pls see in : /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resume_download.php
13. How to compress/zip uploaded file with ZipArchive/pclzip?
pls see in : /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resumes_request.php
14. How to make email template?
pls see in : /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/email.php
then send the email: osc_sendMail($params)
15. How to redirect via javascsript?
pls use like this:
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/helpers.php:
<?php
function job_js_redirect_to($url) { ?>
<script type=”text/javascript”>
window.location = “<?php echo $url; ?>”
</script>
<?php }
and use like this:
job_js_redirect_to(osc_admin_render_plugin_url(“jobboard/manage_killer.php”));
16. How to count/measure elapsed time since the item (is published) until now?
pls see: ‘_jobboard_time_elapsed_string’ function in /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/helpers.php
17. How to count/measure the age/birthday?
pls see: ‘_jobboard_get_age’ function in /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/helpers.php
18. How to use ajax on the item form post/edit?
pls see: /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/killer_form_frm.php
and ‘triggerKillerFormCreation’ javascript function in /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/assets/js/killerForm.js
on action: pls create a new listing and select any category. pls play with ‘Killer Question’ (http://localhost/Projects/osclass_plugin_test/oc-admin/index.php?page=items&action=post)
19. How to get admin user data?
pls use ‘Admin’ static class like this:
$adminManager = Admin::newInstance();
$aAdmin = $adminManager->findByPrimaryKey(osc_logged_admin_id());
pls see: /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/people_detail.php
20. How to find OSClass page?
pls use ‘Page’ static class like this:
$page = Page::newInstance()->findByInternalName(’email_resumes_jobboard’) ;
$page_description = $page[‘locale’] ;
$_title = osc_apply_filter(’email_title’, $page_description[$prefLocale][‘s_title’]);
$_body = osc_apply_filter(’email_description’, $page_description[$prefLocale][‘s_text’]);
pls see: /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resumes_request.php
21. we can render custom ‘user menu’ (the left section that hase some links like : dashboard, profile, account, paymnet, etc) on the user dashboard (like here http://localhost/Projects/kokopage/index.php?page=user&action=items). on the /classer/user-items.php we can display it like this:
<div class=”userMenus boxwhite hasmb”>
<?php echo osc_private_user_menu( get_user_menu() ); ?>
<?php //echo osc_private_user_menu( );//<–default user menu ?>
</div>
Here is the custom ‘user menu’ function ‘get_user_menu’ defined in /classer/functions.php:
function get_user_menu() {
$options = array();
$options[] = array(
‘name’ => __(‘<i class=”icon-certificate”></i> Public Profile’),
‘url’ => osc_user_public_profile_url(),
‘class’ => ‘opt_publicprofile’
);
$options[] = array(
‘name’ => __(‘<i class=”icon-list-numbered”></i> Listings’, ‘classer’),
‘url’ => osc_user_list_items_url(),
‘class’ => ‘opt_items’
);
$options[] = array(
‘name’ => __(‘<i class=”icon-bell-alt”></i> Alerts’, ‘classer’),
‘url’ => osc_user_alerts_url(),
‘class’ => ‘opt_alerts’
);
$options[] = array(
‘name’ => __(‘<i class=”icon-cogs”></i> Account’, ‘classer’),
‘url’ => osc_user_profile_url(),
‘class’ => ‘opt_account’
);
$options[] = array(
‘name’ => __(‘<i class=”icon-mail-2″></i> Change email’, ‘classer’),
‘url’ => osc_change_user_email_url(),
‘class’ => ‘opt_change_email’
);
$options[] = array(
‘name’ => __(‘<i class=”icon-edit-1″></i> Edit username’, ‘classer’),
‘url’ => osc_change_user_username_url(),
‘class’ => ‘opt_change_username’
);
$options[] = array(
‘name’ => __(‘<i class=”icon-key”></i> Change password’, ‘classer’),
‘url’ => osc_change_user_password_url(),
‘class’ => ‘opt_change_password’
);
$options[] = array(
‘name’ => __(‘<i class=”icon-trash”></i> Delete account’, ‘classer’),
‘url’ => ‘#’,
‘class’ => ‘opt_delete_account’
);
return $options;
}
22. How to find out how many ‘paid ads’ or ‘premium ads’?
pls use this: (/classer/inc/user-stats.php)
<?php
$searchPrem = new Search();
$searchPrem->addConditions(sprintf(“b_premium = %d”, 1));
$searchPrem->addConditions(sprintf(“fk_i_user_id = %d”, osc_logged_user_id()));
$searchPrem->limit(0, 1000);//<– dont forget to add ‘limit’. somehow it just came up with 10 data
$premiumItems = $searchPrem->doSearch();
echo count($premiumItems);
?>
somehow i can’t use <?php echo osc_priv_count_premiums(); ?>
23. How to find out how many ‘alerts’?
pls use this: (/classer/inc/user-stats.php)
<?php
$searchAlert = new Search();
$searchAlert->addTable(DB_TABLE_PREFIX.”t_alerts”);
$searchAlert->addConditions(sprintf(“b_active = %d”, 1));
$searchAlert->addConditions(sprintf(“fk_i_user_id = %d”, osc_logged_user_id()));
$searchAlert->limit(0, 1000);//<– dont forget to add ‘limit’. somehow it just came up with 10 data
$alerts = $searchAlert->doSearch();
echo count($alerts);
?>
somehow i can’t use <?php echo osc_count_alerts(); ?>
24. jQuery is not be recognized in certain page (ie. user change email or user change password).
We can include it at the top of those page by using:
osc_enqueue_script(‘jquery-validate’);
note: ‘jquery-validate’ script must exist in the current theme.
25. ‘osc_user_items_validated’ function in /classer/inc/user-stats.php didnt work also on the overlay header. the case is same with above (‘osc_user_id’ didnt give any result so use ‘osc_logged_user_id’ instead):
<?php
if(osc_user_id())
echo osc_user_items_validated();
else{
$searchItem = new Search();
$searchItem->addConditions(sprintf(“b_enabled = %d”, 1));
$searchItem->addConditions(sprintf(“fk_i_user_id = %d”, osc_logged_user_id()));
$searchItem->limit(0, 1000);//<– dont forget to add ‘limit’. somehow it just came up with 10 data
$items = $searchItem->doSearch();
echo count($items);
}
?>
26. Modifying the pagination display:
ref: /plugins/payment/admin/manage.php:
function showingResults(){
$aData = __get(“aData”);
echo ‘<ul class=”showing-results”><li><span>’.osc_pagination_showing((Params::getParam(‘iPage’)-1)*$aData[‘iDisplayLength’]+1, ((Params::getParam(‘iPage’)-1)*$aData[‘iDisplayLength’])+count($aData[‘aRows’]), $aData[‘iTotalDisplayRecords’], $aData[‘iTotalRecords’]).'</span></li></ul>’;
}
osc_add_hook(‘before_show_pagination_admin’,’showingResults’);
osc_show_pagination_admin($aData);
27. Load the items with the pagination:
ref:kokopage/oc-content/plugins/watchlist/watchlist.php
$i_userId = osc_logged_user_id();
if(Params::getParam(‘delete’) != ” && osc_is_web_user_logged_in()){
delete_item(Params::getParam(‘delete’), $i_userId);
}
$itemsPerPage = (Params::getParam(‘itemsPerPage’) != ”) ? Params::getParam(‘itemsPerPage’) : 5;
$iPage = (Params::getParam(‘iPage’) != ”) ? Params::getParam(‘iPage’) : 0;
Search::newInstance()->addConditions(sprintf(“%st_item_watchlist.fk_i_user_id = %d”, DB_TABLE_PREFIX, $i_userId));
Search::newInstance()->addConditions(sprintf(“%st_item_watchlist.fk_i_item_id = %st_item.pk_i_id”, DB_TABLE_PREFIX, DB_TABLE_PREFIX));
Search::newInstance()->addTable(sprintf(“%st_item_watchlist”, DB_TABLE_PREFIX));
Search::newInstance()->page($iPage, $itemsPerPage);
$aItems = Search::newInstance()->doSearch();
$iTotalItems = Search::newInstance()->count();
$iNumPages = ceil($iTotalItems / $itemsPerPage) ;
View::newInstance()->_exportVariableToView(‘items’, $aItems);
View::newInstance()->_exportVariableToView(‘search_total_pages’, $iNumPages);
View::newInstance()->_exportVariableToView(‘search_page’, $iPage) ;
or kokopage/oc-content/plugins/payment/user/menu.php
<?php
$itemsPerPage = (Params::getParam(‘itemsPerPage’) != ”) ? Params::getParam(‘itemsPerPage’) : 4;
$page = (Params::getParam(‘iPage’) != ”) ? Params::getParam(‘iPage’) : 0;
$total_items = Item::newInstance()->countByUserID(osc_logged_user_id());
$total_pages = ceil($total_items/$itemsPerPage);
$items = Item::newInstance()->findByUserID(osc_logged_user_id(), $page * $itemsPerPage, $itemsPerPage);
View::newInstance()->_exportVariableToView(‘items’, $items);
View::newInstance()->_exportVariableToView(‘list_total_pages’, $total_pages);
View::newInstance()->_exportVariableToView(‘list_total_items’, $total_items);
View::newInstance()->_exportVariableToView(‘items_per_page’, $itemsPerPage);
View::newInstance()->_exportVariableToView(‘list_page’, $page);
?>
or /plugins/mb_auction/themes/default/auction_dashboard_widget.php:
$itemsPerPage = (Params::getParam(‘itemsPerPage’)!=”)?Params::getParam(‘itemsPerPage’):10;
$page = (Params::getParam(‘iPage’) > 0) ? Params::getParam(‘iPage’) -1 : 0;
Search::newInstance()->addTable(sprintf(“%st_item_auction”, DB_TABLE_PREFIX));
Search::newInstance()->addConditions(sprintf(“%st_item.pk_i_id = %st_item_auction.fk_i_item_id “, DB_TABLE_PREFIX, DB_TABLE_PREFIX));
Search::newInstance()->addConditions(sprintf(“%st_item.fk_i_user_id = “.osc_logged_user_id(), DB_TABLE_PREFIX));
Search::newInstance()->order(sprintf(“%st_item.pk_i_id”, DB_TABLE_PREFIX),’DESC’,”);
Search::newInstance()->page($page, $itemsPerPage);
$aItems = Search::newInstance()->doSearch();
$iTotalItems = Search::newInstance()->count();
$iNumPages = ceil($iTotalItems / $itemsPerPage) ;
View::newInstance()->_exportVariableToView(‘items’, $aItems);
View::newInstance()->_exportVariableToView(‘search_total_pages’, $iNumPages);
View::newInstance()->_exportVariableToView(‘search_page’, $page) ;
29. If we manually loop some items and we want to show the items properties (like title, description, images, etc), usually we can do it by using like this:
<?php foreach($payments as $pay) { ?>
…
<?php
$itemId=$pay[‘fk_i_item_id’];
if($itemId != 0){
View::newInstance()->_exportVariableToView(“item”, Item::newInstance()->findByPrimaryKey($itemId));
…
?>
<?php if(osc_count_item_resources()) { ?>
<div class=”img”>
<a class=”listing-thumb” href=”<?php echo osc_item_url() ; ?>” title=”<?php echo osc_esc_html(osc_item_title()) ; ?>”>
<img src=”<?php echo osc_resource_thumbnail_url(); ?>” title=”” alt=”<?php echo osc_esc_html(osc_item_title()) ; ?>” width=”<?php echo $size[0]; ?>” height=”<?php echo $size[1]; ?>”>
</a>
</div>
<?php } else { ?>
<div class=”img”>
<a class=”listing-thumb” href=”<?php echo osc_item_url() ; ?>” title=”<?php echo osc_esc_html(osc_item_title()) ; ?>”>
<img src=”<?php echo osc_current_web_theme_url(‘images/no_photo.gif’); ?>” title=”” alt=”<?php echo osc_esc_html(osc_item_title()) ; ?>” width=”<?php echo $size[0]; ?>” height=”<?php echo $size[1]; ?>”>
</a>
</div>
<?php } ?>
<?php
…
}
?>
<?php } ?>
BUT IF WE DID LIKE ABOVE WE’D FIND THE SAME IMAGE FOR EACH ITEM. THIS IS HAPPENED BECAUSE WE FORGET TO CLEAR THE ‘resources’ KEY FROM THE PREVIOUS ITEM!!!. SO DO LIKE THIS:
<?php foreach($payments as $pay) { ?>
<?php
if(View::newInstance()->_exists(‘item’))
View::newInstance()->_erase(‘item’);
if(View::newInstance()->_exists(‘resources’))
View::newInstance()->_erase(‘resources’);
$itemId=$pay[‘fk_i_item_id’];
if($itemId != 0){
View::newInstance()->_exportVariableToView(“item”, Item::newInstance()->findByPrimaryKey($itemId));
…
?>
View::newInstance()->_erase(‘resources’) WILL CLEAR THE PREVIOUS ‘resources’ KEY, SO ‘osc_count_item_resources’ function WOULD LOAD THE NEW ONE. PLS SEE ‘osc_count_item_resources’ function code in /oc-includes/osclass/helpers/hItems.php
ref:/plugins/payment/user/user-payment-list.php
link:http://localhost/Projects/kokopage/index.php?page=custom&route=user-payment-list-url
30. When we use ‘osc_redirect_to’ function, sometime we get some warning:
‘Warning: Cannot modify header information – headers already sent by…’
then we use ‘header’ instead. I THINK WE STILL CAN USE ‘osc_redirect_to’ function by adding ‘ob_get_clean()’ function on the previous line like this: (TODO: NEED TEST!!!)
…
// HACK : This will make possible use of the flash messages 😉
ob_get_clean();
osc_add_flash_ok_message(__(‘Congratulations, the plugin is now configured’, ‘cookie’), ‘admin’);
osc_redirect_to(osc_route_admin_url(‘cookie-conf’));
ref:/plugins/cookies/admin/conf.php
31. IS A CUSTOM HOOK BEHAVIOUR LIKE GLOBAL FUNCTIONS????? IT CAN BE CALLED FROM ANYWHERE???
32. Customized get latest Items
View::newInstance()->_exportVariableToView(‘items’, $osclassItems);
if(osc_is_home_page()) {
$latestSearch = new Search();
$latestSearch->limit (0, osc_get_preference(‘maxLatestItems@home’, ‘osclass’));
$latestItems = $latestSearch->getLatestItems();
View::newInstance()->_exportVariableToView(‘items’, $latestItems);
}
ref:/osclass_plugin_test/oc-content/plugins/carousel_for_osclass/carousel_detail.php
33. How to validate form input on the plugins (for plugin admin page also)
Register and enqueue ‘jquery-validate’ on the init hook like this:
ref:/osclass.3.5.9/oc-content/plugins/mb_auction/index.php
function mb_auction_load_js_css() {
…
osc_register_script(‘auction_js’, mb_auction_plugin_directory().’js/auction.js’, ‘jquery’);
osc_register_script(‘jquery-validate’, osc_base_url() . ‘oc-includes/osclass/assets/js/jquery.validate.min.js’, ‘jquery’);
osc_register_script(‘jquery-validate-additional’, mb_auction_plugin_directory().’js/additional-methods.min.js’, array(‘jquery’, ‘jquery-validate’,’jquery-ui’));
…
osc_enqueue_script(‘auction_js’);
osc_enqueue_script(‘jquery-validate’);
osc_enqueue_script(‘jquery-validate-additional’);
osc_enqueue_style(‘auctionCss’, mb_auction_plugin_directory().’css/style.css’);
}
then you can use it anywhere on your plugin:
ref:/osclass.3.5.9/oc-content/plugins/mb_auction/admin/manage.php
<script type=”text/javascript”>
$(document).ready(function() {
$.validator.addMethod(‘min_lower_max’,function(value,element){
return value <= parseInt($(“#max_auction_length”).val());
},'<?php echo osc_esc_js(__(“Minimum Auction Length (Days) should be lower than Maximum Auction Length (Days)”, “mb_auction”)); ?>.’);
$.validator.addMethod(‘max_greater_min’,function(value,element){
return value >= parseInt($(“#min_auction_length”).val());
},'<?php echo osc_esc_js(__(“Maximum Auction Length (Days) should be greater than Minimum Auction Length (Days)”, “mb_auction”)); ?>.’);
$(‘form#mb_auction_form’).validate({
rules: {
min_auction_length: {
required: true,
number: true,
min: 1,
min_lower_max: true
},
max_auction_length: {
required: true,
number: true,
min: 1,
max_greater_min: true
},
min_auction_increment_price: {
required: true,
number: true,
min: 0
}
},
messages: {
min_auction_length: {
required: ‘<?php echo osc_esc_js(__(“Minimum Auction Length (Days)”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“this field is required”, “mb_auction”)); ?>.’,
number: ‘<?php echo osc_esc_js(__(“Minimum Auction Length (Days)”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“enter valid number”, “mb_auction”)); ?>.’,
min: ‘<?php echo osc_esc_js(__(“Minimum Auction Length (Days)”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“Minimum length is “, “mb_auction”)); ?>1.’
},
max_auction_length: {
required: ‘<?php echo osc_esc_js(__(“Maximum Auction Length (Days)”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“this field is required”, “mb_auction”)); ?>.’,
number: ‘<?php echo osc_esc_js(__(“Maximum Auction Length (Days)”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“enter valid number”, “mb_auction”)); ?>.’,
min: ‘<?php echo osc_esc_js(__(“Maximum Auction Length (Days)”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“Minimum length is “, “mb_auction”)); ?>1.’
},
min_auction_increment_price: {
required: ‘<?php echo osc_esc_js(__(“Minimum Auction Increment Price”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“this field is required”, “mb_auction”)); ?>.’,
number: ‘<?php echo osc_esc_js(__(“Minimum Auction Increment Price”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“enter valid price”, “mb_auction”)); ?>.’,
min: ‘<?php echo osc_esc_js(__(“Minimum Auction Increment Price”, “mb_auction”)); ?>: <?php echo osc_esc_js(__(“Minimum price is “, “mb_auction”)); ?>0.’
}
},
errorLabelContainer: “#error_list”,
wrapper: “li”,
invalidHandler: function(form, validator) {
$(‘html,body’).animate({ scrollTop: $(‘h1’).offset().top }, { duration: 250, easing: ‘swing’});
},
submitHandler: function(form){
$(‘button[type=submit], input[type=submit]’).attr(‘disabled’, ‘disabled’);
form.submit();
}
});
});
</script>
34. more complex jquery validate implementation:
ref:motobroker/oc-content/themes/tuffclassified/user-register.php
<script>
$( document ).ready(function() {
$(“#s_email2”).attr(“autocomplete”,”off”);
$(“form[name=register]”).validate({
rules: {
s_fname: {
required: true,
minlength: 2
},
s_lname: {
required: true,
minlength: 2
},
s_email: {
required: true,
email: true
},
s_email2: {
required: true,
email: true,
equalTo: “#s_email”
},
s_password: {
required: true,
minlength: 5
},
s_password2: {
required: true,
minlength: 5,
equalTo: “#s_password”
}
<?php
if(in_array(“mb_memberships/index.php”,$plugins_list)){
?>
,
agree: {
required: {
depends: function(element) {
return $(“#seller_type”).val()==”DEALER”;
}
}
},
dealer_name: {
required: {
depends: function(element) {
return $(“#agree”).is(“:checked”);
}
},
minlength: 3
},
dealer_country: {
required: true
},
dealer_region: {
required: true
},
dealer_city: {
required: true
},
dealer_address: {
required: {
depends: function(element) {
return $(“#agree”).is(“:checked”);
}
},
minlength: 5
},
dealer_phone: {
required: {
depends: function(element) {
return $(“#agree”).is(“:checked”);
}
},
minlength: 5
},
dealer_license: {
required: {
depends: function(element) {
return $(“#agree”).is(“:checked”);
}
},
minlength: 5
},
dealer_logo: {
required: {
depends: function(element) {
return $(“#agree”).is(“:checked”) && $(“#dealer_logo”).val() != “”;
}
},
accept: “image/*”,
extension: “png|jpg|gif”
},
dealer_logo_size: {
required: {
depends: function(element) {
return $(“#agree”).is(“:checked”) && $(“#dealer_logo”).val() != “”;
}
},
max: 105000
},
dealer_about: {
required: {
depends: function(element) {
return $(“#agree”).is(“:checked”);
}
},
minlength: 5
},
<?php
}
?>
},
messages: {
s_fname: {
required: “<?php _e(“First Name: this field is required”); ?>.”,
minlength: “<?php _e(“Enter at least 2 characters”); ?>.”
},
s_lname: {
required: “<?php _e(“Last Name: this field is required”); ?>.”,
minlength: “<?php _e(“Enter at least 2 characters”); ?>.”
},
s_email: {
required: “<?php _e(“Email: this field is required”); ?>.”,
email: “<?php _e(“Invalid email address”); ?>.”
},
s_email2: {
required: “<?php _e(“Email: this field is required”); ?>.”,
email: “<?php _e(“Invalid email address”); ?>.”,
equalTo: “<?php _e(“Email don’t match”); ?>.”
},
s_password: {
required: “<?php _e(“Password: this field is required”); ?>.”,
minlength: “<?php _e(“Password: enter at least 5 characters”); ?>.”
},
s_password2: {
required: “<?php _e(“Second password: this field is required”); ?>.”,
minlength: “<?php _e(“Second password: enter at least 5 characters”); ?>.”,
equalTo: “<?php _e(“Passwords don’t match”); ?>.”
}
<?php
if(in_array(“mb_memberships/index.php”,$plugins_list)){
?>
,
agree: {
required: “<?php _e(“Please check ‘Agree’ for user dealer”); ?>.”
},
dealer_country: {
required: “<?php _e(“Country: this field is required”); ?>.”
},
dealer_region: {
required: “<?php _e(“Region/State: this field is required”); ?>.”
},
dealer_city: {
required: “<?php _e(“City/Suburb: this field is required”); ?>.”
},
dealer_name: {
required: “<?php _e(“Name: this field is required”); ?>.”,
minlength: “<?php _e(“Enter at least 3 characters”); ?>.”
},
dealer_address: {
required: “<?php _e(“Address: this field is required”); ?>.”,
minlength: “<?php _e(“Enter at least 3 characters”); ?>.”
},
dealer_phone: {
required: “<?php _e(“Phone Number: this field is required”); ?>.”,
minlength: “<?php _e(“Enter at least 3 characters”); ?>.”
},
dealer_license: {
required: “<?php _e(“License Number: this field is required”); ?>.”,
minlength: “<?php _e(“Enter at least 3 characters”); ?>.”
},
dealer_logo: {
accept: “<?php _e(“Accept only image file (jpg, png or gif)”); ?>.”,
extension: “<?php _e(“Accept only image file with these extensions (jpg, png or gif)”); ?>.”
},
dealer_logo_size: {
max: “<?php _e(“Maximum image size is 100kb”); ?>.”
},
dealer_about: {
required: “<?php _e(“About Us: this field is required”); ?>.”,
minlength: “<?php _e(“Enter at least 3 characters”); ?>.”
}
<?php
}
?>
},
highlight: function(element) {
$(element).closest(‘.form-group’).addClass(‘has-warning’);
},
unhighlight: function(element) {
$(element).closest(‘.form-group’).removeClass(‘has-warning’);
},
errorElement: ‘span’,
errorClass: ‘help-block’,
errorPlacement: function(error, element) {
if(element.parent(‘.input-group’).length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
if($(“span[for=’s_fname’]”).length && $(“span[for=’s_lname’]”).length){
$(“span[for=’s_fname’]”).prependTo(“span[for=’s_lname’]”);
}
},
success: function() {
var fname=$(“#s_fname”).val().trim();
var lname=$(“#s_lname”).val().trim();
$(“#s_name”).val(fname+” “+lname);
}
});
});
</script>
OSCLASS FUNCTIONS:
1. osc_highlight
note: to display some portion of text
use: osc_highlight(@$item[‘s_title’],30) //just display 30 char
2. osc_admin_render_plugin_url
note: to display the current plugin url on admin page (usually it is used in <a> tag)
use: <a href=”‘.osc_admin_render_plugin_url(“jobboard/people.php”).’&iStatus=’.$k.'”>’.__(‘View all’,’jobboard’).’ ‘.$v.'</a>
or
job_js_redirect_to(osc_admin_render_plugin_url(“jobboard/manage_killer.php”));
to display the current plugin url on front page, pls use ‘osc_plugin_folder’ like this:
<a href=”#” class=”star” star=”‘.$k.'” id=”rating_’.$applicantId.’_’.$k.'” ><img src=”‘.osc_base_url().’oc-content/plugins/’.osc_plugin_folder(__FILE__).’img/’.($k<=$rating?’fullstar.png’:’emptystar.png’).'”/></a>
3. osc_admin_base_url
note: to display base admin page url (with ‘true’ would display also index.php)
use: <a href=”<?php echo osc_admin_base_url(true); ?>?page=items” style=”text-decoration:none;”>
4. osc_is_admin_user_logged_in
note: only logged in admin can use/enter/access
use: if(!osc_is_admin_user_logged_in()) {
die;
}
5. osc_die
note: is it same with ‘die()’ ??? but we can write something at the end;
use: osc_die($title, $message);
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/download.php:
6. osc_sanitizeString
note: remove empty string/space in a text??
use:$filename = osc_sanitizeString($applicant[‘s_name’]);
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/download.php:
7. osc_max_images_per_item
note: display how many image can be uploaded for an item
use: if( osc_max_images_per_item() > 0 ) {
osc_set_preference(‘numImages@items’, 0);
}
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/helpers.php:
8. osc_item_attachment
note : display/check if this item has any attachment
use: if( !osc_item_attachment() ) {
osc_set_preference(‘item_attachment’, true);
}
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/helpers.php:
9. osc_price_enabled_at_items
note : check if this item can be put any price
use: if( osc_price_enabled_at_items() ) {
osc_set_preference(‘enableField#f_price@items’, false);
}
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/helpers.php:
10. osc_images_enabled_at_items
note : check if this item can be uploaded any image
use: if( osc_images_enabled_at_items() ) {
osc_set_preference(‘enableField#images@items’, false);
}
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/helpers.php:
11. osc_plugin_path
note: to display url for the current plugin (may be better for ‘hook’ and ‘register’ plugin)
use:
osc_register_plugin(osc_plugin_path(__FILE__), array( new JobboardInstallUpdate(), ‘job_call_after_install’) );
osc_add_hook(osc_plugin_path(__FILE__).”_uninstall”, array( new JobboardInstallUpdate(), ‘job_call_after_uninstall’) );
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/index.php:
for ‘register’ script (js/css), pls use ‘osc_plugin_url’ like this:
osc_register_script(‘jquery-rating’, osc_plugin_url(__FILE__) . ‘assets/lib/rating/jquery.rating.js’, ‘jquery’);
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/index.php:
12. osc_current_user_locale
note: find the locale language
use: $locale = osc_current_user_locale();
$detail[‘locale’][$locale][‘s_studies’]
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/item_detail.php:
13. osc_get_locales
note: find all language installed
use: foreach(osc_get_locales() as $locale) {
echo $locale[‘pk_c_code’];
}
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/item_edit.php:
13. osc_language
note: find the current language??
use:
$prefLocale = osc_language() ;
$_title = osc_apply_filter(’email_title’, $page_description[$prefLocale][‘s_title’]);
ref:/osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resumes_request.php:
14. osc_esc_html
note: display a text with html tag ??
use: echo osc_esc_html(__(‘Delete question’, ‘jobboard’));
15. osc_doRequest
note:???
use: pls see in /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resume_download.php
if(Params::getParam(‘paction’)==’createpack’) {
$params = array(
‘page’ => ‘ajax’
,’action’ => ‘custom’
,’ajaxfile’ => osc_plugin_folder(__FILE__).”resumes_request.php”
);
osc_doRequest(osc_base_url(), $params);
}
16. osc_add_filter and osc_apply_filter
ref: /oc-includes/osclass/helpers/hPlugins.php
ref: /oc-includes/osclass/classes/Plugins.php (applyFilter)
note: to modify the osclass filter content with the user defined function/text???
use:
function applicant_admin_menu_current($class) {
if( urldecode(Params::getParam(‘file’)) === ‘jobboard/people_detail.php’ ) {
return ‘current’;
}
return $class;
}
osc_add_filter(‘current_admin_menu_corporateboard’, ‘applicant_admin_menu_current’);//predefined function
use:
$_title = osc_apply_filter(’email_title’, $page_description[$prefLocale][‘s_title’]);//predefined text
ref: /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resumes_request.php
if we want to set a hook content as empty??? with no predefined function/callback and text, we can do like this:
osc_add_filter(‘bender_bodyClass’,’bender_add_body_class_construct’);
$classes = osc_apply_filter(‘bender_bodyClass’, array());
ref: /osclass_plugin_test/oc-content/themes/bender/functions.php
learn (also for osc_add_hook and osc_run_hook):
func_get_args() //Returns an array comprising a function’s argument list. pls see:http://php.net/manual/en/function.func-get-args.php
and
call_user_func_array() //Call a callback with an array of parameters. pls see:http://php.net/manual/en/function.call-user-func-array.php
17. osc_logged_admin_name and osc_logged_admin_id
note: find admin username and id respectively
use:
echo osc_logged_admin_name()
echo osc_logged_admin_id()
when send email from admin, we can do like this:
$words[] = array(
osc_logged_admin_name()
,$list
);
ref: /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resumes_request.php
18. osc_mailBeauty
note: beautify/tidify email content???
use:
$title = osc_mailBeauty($_title, $words);
$body = osc_mailBeauty($_body , $words);
ref: /osclass_plugin_test/oc-content/plugins/plugin-jobboard-master/resumes_request.php
19. Params::getParamsAsArray()
20. osc_is_web_user_logged_in(), osc_logged_user_id()
21. osc_esc_js
note: display translation for javascript/jquery
use: $(“#available”).text(‘<?php echo osc_esc_js(__(“The username is available”, “bender”)); ?>’);
ref: /themes/bender/user-change_username.php
OSCLASS PROBLEMS & SOLUTIONS :
1. Problem : homepage/admin show blank page
Solution : Put define(‘OSC_DEBUG’, true) ; in config.php and refresh browser. pls see the error/warning output
or chmod 777 -R the osclass directory
or check again config.php (at part REL_WEB_URL and WEB_PATH)
2. Problem : front page show “We are sorry for any inconvenience. MyPage is undergoing maintenance.”
Solution : go to admin page (/oc-admin) on the browser then Show more -> Tools -> Maintenance mode then click “Disable maintenance mode”
then refresh again the front page
3. Problem : Warning : cannot open ‘HTMLPurifier/Bootstrap.php’. failed to open in …..
Solution : May be you just renamed the directory of the osclass project and the osclass cache still intact. pls change back the directory name and refresh
4. Problem : The requested URL /index.php was not found on this server.(can’t open url-friendly page)
Solution : check again your .htaccess
if the root of osclass in a sub directory, so change from
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
Options -MultiViews
</IfModule>
to (for example)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /Projects/motobroker/
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /Projects/motobroker/index.php [L]
</IfModule>
5. Problem : Can’t open the plugin link. for example this link : http://motobroker.dev/oc-admin/index.php?page=plugins&action=renderplugin&route=mb-facebook-manage§ion=facebook just open a blank content
Solution : Check another plugin for the same route name. for example in mb_auction, there is ‘mb-facebook-manage’ route. after searching in another plugin, there is a same route in get_my_listing plugin. Pls change/rename the route in one of the plugin.
6. Add/attach ‘image’ (also how many image can be attached) and/or add ‘Price’ was not displayed on the item post/edit page
Solution: There is a setting in admin page -> Listings -> Settings (or by url:http://localhost/Projects/osclass_plugin_test/oc-admin/index.php?page=items&action=settings)
Pls check on ‘Optional fields’ : ‘Attach Images’ and ‘Price’
To set how many image can be attached, pls fill the ‘Attach ### images per listing’
LEARN THIS!!
HOW ‘wallet_button’ function defined in /plugins/payment/functions.php CAN BE CALLED FROM /plugins/promote_ad/user/payment.php???
THE SAME CASE FOR ‘Paypal::button’ static function defined in /plugins/payment/payments/paypal/Paypal.php ??
THE SAME CASE FOR ‘StripePayment::button’ static function defined in /plugins/payment/payments/stripe/StripePayment.php ???
SOLUTION!!!
In /plugins/payment/index.php, THOSE FUNCTIONS ALREADY INCLUDED GLOBALLY! LIKE THIS:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
... define('PAYMENT_CRYPT_KEY', 'anewrandompass12'); // PAYMENT STATUS define('PAYMENT_FAILED', 0); define('PAYMENT_COMPLETED', 1); define('PAYMENT_PENDING', 2); define('PAYMENT_ALREADY_PAID', 3); // load necessary functions require_once osc_plugins_path() . osc_plugin_folder(__FILE__) . 'functions.php'; //for calling wallet_button require_once osc_plugins_path() . osc_plugin_folder(__FILE__) . 'ModelPayment.php'; // Load different methods of payments if(osc_get_preference('paypal_enabled', 'payment')==1) { require_once osc_plugins_path() . osc_plugin_folder(__FILE__) . 'payments/paypal/Paypal.php'; //for calling Paypal::button } ... if(osc_get_preference('stripe_enabled', 'payment')==1) { require_once osc_plugins_path() . osc_plugin_folder(__FILE__) . 'payments/stripe/StripePayment.php'; //for calling StripePayment::button osc_add_hook('ajax_stripe', array('StripePayment', 'ajaxPayment')); } ... |
SO WHEN THE payment PLUGIN IS LOADED, ANOTHER PLUGIN CAN CALL THE FUNCTION???
WHAT IS THE DIFFERENT WITH osc_add_hook(‘init’, ‘payment_load_lib’);???
OR osc_add_hook(osc_plugin_path(__FILE__).”_enable”, ‘payment_update_version’);???
SETUP OSCLASS 3.7.4 WITH NGINX AND PHP7.0-FPM ON UBUNTU 16.04
ref: https://www.mindstellar.com/osclass-nginx-php-fpm-better-performance
- Create the config file
1sudo gedit /etc/nginx/sites-available/osclass374.test
Here is the content:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283server {listen 80;listen [::]:80;root /home/teddy/Documents/works/osclass374; #your document rootserver_name www.osclass374.test osclass374.test ; # Your server nameindex index.php index.html index.htm ;# Webfonts,fontslocation ~* \.(?:ttf|ttc|otf|eot|woff|woff2)$ {add_header "Access-Control-Allow-Origin" "*";expires 1y;access_log off;add_header Cache-Control "public";}# Media: images, icons, video, audio, HTClocation ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {expires 1y;access_log off;add_header Cache-Control "public";}# Js, Csslocation ~* \.(?:css|js)$ {expires 1y;access_log off;add_header Cache-Control "public";}# Serve static files without touching phplocation / {try_files $uri $uri/ /index.php?$args;}# pass requests for dynamic content to sitelocation ~ [^/]\.php(/|$) {try_files $uri /index.php;fastcgi_pass unix:/run/php/php7.0-fpm.sock;fastcgi_buffers 1024 4k;fastcgi_read_timeout 600s;fastcgi_connect_timeout 600s;fastcgi_index index.php;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;#include fastcgi_params;#FOR DEVELOPMENT MODE ONLY - BEGINfastcgi_param MAGE_IS_DEVELOPER_MODE true;fastcgi_param PHP_VALUE display_startup_errors=on;fastcgi_param PHP_VALUE display_errors=on;fastcgi_param PHP_VALUE html_errors=on;fastcgi_param PHP_VALUE log_errors=on;fastcgi_param PHP_VALUE error_log=/home/teddy/Documents/works/osclass374/var/log/system.log;#FOR DEVELOPMENT MODE ONLY - ENDinclude fastcgi_params;}gzip on;gzip_disable "msie6";gzip_comp_level 6;gzip_min_length 1100;gzip_buffers 16 8k;gzip_proxied any;gzip_typestext/plaintext/csstext/jstext/xmltext/javascriptapplication/javascriptapplication/x-javascriptapplication/jsonapplication/xmlapplication/xml+rssimage/svg+xml;gzip_vary on;# Banned locations (only reached if the earlier PHP entry point regexes don't match)location ~* (\.php$|\.htaccess$|\.git) {deny all;}} - Enable file config
1sudo ln -s /etc/nginx/sites-available/osclass374.test /etc/nginx/sites-enabled/osclass374.test - Register the host on my system
1sudo gedit /etc/hosts
Like this:
123...127.0.0.1 osclass374.test... - CHECK THE NGINX SETTING AND RESTART IT:
123teddy@teddy:~$ sudo nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
1sudo systemctl restart nginx
- Set file permission and owner:
1teddy@teddy:~/Documents/works$ sudo chown www-data:www-data -R osclass374/
Test: http://osclass374.test/ –> WORKING
http://osclass374.test/oc-admin –> user: admin; pass: admin - USE API
ref: https://github.com/jun283/aRestAPI4Osclass
Download the code (zip) then extract in osclass root directory. It’d be better to rename the extracted dir to ‘api’. So it’d be /osclass374/api/v0.1/…Then modify nginx config to enable the API endpoint calling
1sudo gedit /etc/nginx/sites-available/osclass374.test
Modify like this (add location /api/v0.1/):
ref: https://stackoverflow.com/questions/29087426/how-to-configure-rewrite-rules-for-small-api-using-nginx
1234567891011121314151617181920212223242526...# Serve static files without touching phplocation / {try_files $uri $uri/ /index.php?$args;}# Handle api/v0.1 sub projectlocation /api/v0.1/ {# Debug output#return 200 $args; add_header Content-Type text/plain;# Root for this sub project#root /var/www/api-v1/public;# Rewrite $uri=/api/v1/xyz back to just $uri=/xyzrewrite ^/api/v0.1/(.*)/?$ /api/v0.1/index.php?uri=$1 last;# Try to send static file at $url or $uri/# Else try /index.php (which will hit location ~\.php$ below)#try_files $uri $uri/ /index.php?$args;}# pass requests for dynamic content to sitelocation ~ [^/]\.php(/|$) {...}
Save then Restart nginx
Test like this: (SEARCH THE LIST OF END POINT IN /home/teddy/Documents/works/osclass374/api/v0.1/apiServer.php FILE)
http://osclass374.test/api/v0.1/category/
it’d give output(json):
12345678910111213141516171819202122232425262728293031323334353637[{"pk_i_id": "1","fk_i_parent_id": null,"i_expiration_days": "0","i_position": "1","b_enabled": "1","b_price_enabled": "1","s_icon": null,"fk_i_category_id": "1","fk_c_locale_code": "en_US","s_name": "For sale","s_description": null,"s_slug": "for-sale","i_num_items": "1"},{"pk_i_id": "2",......},{"pk_i_id": "95","fk_i_parent_id": "8","i_expiration_days": "0","i_position": "21","b_enabled": "1","b_price_enabled": "1","s_icon": null,"fk_i_category_id": "95","fk_c_locale_code": "en_US","s_name": "Other Jobs","s_description": null,"s_slug": "other-jobs","i_num_items": "0"}]
http://osclass374.test/api/v0.1/category/9
it’d give output (json):
1234567891011121314151617[{"pk_i_id": "9","fk_i_parent_id": "1","i_expiration_days": "0","i_position": "1","b_enabled": "1","b_price_enabled": "1","s_icon": null,"fk_i_category_id": "9","fk_c_locale_code": "en_US","s_name": "Animals","s_description": null,"s_slug": "animals","i_num_items": "1"}]