Хак Только код

_kot

Продвинутый (IV)
Сообщения
17
Симпатии
20
Баллы
486
В этой теме предлагаю добавлять "хаки" для расширения функционала.
Делимся кодом и не флудим тему.

Osclass - поиск юзера и его объявлений.
В файл function.php, вашей темы, в самом низу, добавил следующее
PHP:
//mod sz wildcard search
function search_wildcard_usrname($params) {

    if (@$params['sPattern']) {
        $mSearch =  Search::newInstance();
        $query_elements = (array) json_decode($mSearch->toJson());
        $pattern = $query_elements['sPattern'];
        $query_elements['sPattern'] = str_replace(' ', '* ', $pattern) . '*';
        $mSearch->setJsonAlert($query_elements);

        // username search
        $aPattern = explode(' ', $pattern);
        $userNameCond = '';

        foreach ($aPattern as $word) {
            if ($word) $userNameCond .= sprintf(" || %st_item.s_contact_name LIKE '%s%%'", DB_TABLE_PREFIX, $word);
        }

        $mSearch->addConditions("1 = 1 " . $userNameCond);
        $mSearch->addGroupBy(DB_TABLE_PREFIX.'t_item.pk_i_id');
    }
}

osc_add_hook('search_conditions', 'search_wildcard_usrname', 1);
 
Последнее редактирование:
Когда пользователь заходит на сайт и начинает что-то искать или заходить и читать объявления, его может посетить мысль разместить объявления. По статистике юзер размещает в той же категории где ищет.
Давайте отследим где находится юзер, в какой категории и поможем ему с автозаполнением категории, если он решит разместить объявление

В файле function.php вашей темы в самом низу добавим код
PHP:
function sz_item_post_url_in_category() {

    $search_cat_id = osc_search_category_id();
    $search_cat_id = isset($search_cat_id[0]) ? $search_cat_id[0] : 0;
    $search_cat_parent = Category::newInstance()->findByPrimaryKey($search_cat_id);
    $search_cat_parent =   $search_cat_parent['fk_i_parent_id'];
    osc_selectable_parent_categories() ? $allow_cat_parent = true :  $allow_cat_parent  = false;

    if ($search_cat_id && $search_cat_parent  || osc_is_ad_page()  || $allow_cat_parent) {

        if ( osc_rewrite_enabled() ) {

            osc_is_ad_page()   ?   $path = osc_base_url() . osc_get_preference('rewrite_item_new') . '/' . osc_item_category_id()
                            :   $path = osc_base_url() . osc_get_preference('rewrite_item_new') . '/' . osc_search_category_id()[0];
        } else {
            osc_is_ad_page()   ?   $path = sprintf(osc_base_url(true) . '?page=item&action=item_add&catId=%d', osc_item_category_id())
                            :   $path = sprintf(osc_base_url(true) . '?page=item&action=item_add&catId=%d', osc_search_category_id()[0]);
        }

    } else {

            //default url
            $path = osc_item_post_url();

    }
    return $path;
}

В файлах вашей темы находим osc_item_post_url(); и меняем на sz_item_post_url_in_category();


В большинстве тем для моб версий используется JS, что-бы это работало везде добавим немного кода )
В файле head.php найдем любой JS, там объявим переменные
JavaScript:
var osc_selectable_parent_categories = '<?php echo osc_selectable_parent_categories() ? 1 : 0 ; ?>';
var osc_is_search_page = '<?php echo osc_is_search_page() ? 1 : 0; ?>';
var osc_rewrite_enabled = '<?php echo osc_rewrite_enabled() ? 1 : 0; ?>';
var osc_item_post_url = '<?php echo osc_item_post_url(); ?>';

Дальше добавим код в основной JS файл вашей темы, это может быть global.js, main.js и т.д.
Код:
if (osc_is_search_page == 1) {

        $("a#myBtn, a.publish").click(function (e) {
            e.preventDefault();
            catId = document.getElementById("sCatId").value;
            mainCat = document.getElementById("sMainCategory").value;

            if (osc_rewrite_enabled == 1) {

                if (mainCat == 0 && osc_selectable_parent_categories == 0) {
                    window.location.replace(osc_item_post_url);
                } else if (osc_selectable_parent_categories == 1) {
                    window.location.replace(osc_item_post_url + '/' + catId);
                } else {
                    window.location.replace(osc_item_post_url + '/' + catId);
                }

            } else {

                if (mainCat == 0 && osc_selectable_parent_categories == 0) {
                    window.location.replace(osc_item_post_url);
                } else if (osc_selectable_parent_categories == 1) {
                    window.location.replace(osc_item_post_url + '&catId=' + catId);
                } else {
                    window.location.replace(osc_item_post_url + '&catId=' + catId);
                }


            }

        });
    }

Селекторы как - a#myBtn, a.publish для каждой темы разные
Принцип в общем ясен ! )
 
Последнее редактирование:
Как определенному зарегистрированному пользователю по ("user name" или по "user id") в аккаунте во время добавления объявления, скрыть определенную категорию в выпадающем списке - например (скрыть для пользователя с ID - 12 категорию <option value="4">Cars</option>).

В примере ID категории - 4
user ID - 12

Тема BETA.
------------------------
РНР для опредиления user_id

<?php if(osc_logged_user_id() == 12) { ?>

<?php } ?>
------------------------
jQuery опредиляет какуб категорию из выпадающего списка удалить value='4'

<script>
$(document).ready(function(){
$("#select_1 option[value='4']").remove();
});
</script>
------------------------
Полный код:

<?php if(osc_logged_user_id() == 12) { ?>
<script>
$(document).ready(function(){
$("#select_1 option[value='2']").remove();
});
</script>
<?php } ?>
 
Как на главной в main.php (последние объявления) вывести определенную категорию.
ТЕМА ВЕТА - категория с id "4"
Код:
<div class="home-container latest">
    <div class="inner">

      <!-- LATEST LISTINGS BLOCK -->
      <div id="latest" class="products grid">
        <h2><?php _e('Lately added on our classifieds', 'beta'); ?></h2>

        <?php osc_query_item(array("category" => "4")); ?>

        <?php if( osc_count_custom_items() > 0) { ?>
          <div class="block">
            <div class="prod-wrap">
              <?php $c = 1; ?>
              <?php while( osc_has_custom_items() ) { ?>
                <?php bet_draw_item($c); ?>
              
                <?php $c++; ?>
              <?php } ?>
            </div>
          </div>
      
        <?php } else { ?>
          <div class="home-empty">
            <img src="<?php echo osc_current_web_theme_url('images/home-empty.png'); ?>" />
            <strong><?php _e('No listing in category yet', 'beta'); ?></strong>
          </div>
        <?php } ?>

        <?php View::newInstance()->_erase('items') ; ?>
      </div>
    </div>
  </div>
 
Как сделать вывод атрибутов в поиске frontend
Добавить в loop-single.php Темы.

Код:
<div class="custom-fields">
<?php if( osc_count_item_meta() >= 1 ) { ?>
<div class="meta_list">
<?php while ( osc_has_item_meta() ) { ?>
<?php if(osc_item_meta_value()!='') { ?>
<div class="meta">
<strong><?php echo osc_item_meta_name(); ?>:</strong> <span class="value"><?php echo osc_item_meta_value(); ?></span>
</div>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
</div>
 
Отобразить количество объявлений.
По пути:
--> /oc-content/plugins/list_seller_items --> index.php

Код:
function seller_post() {
  if(osc_get_preference('rewriteEnabled', 'osclass') <> 1) {
    $url = osc_base_url() . 'index.php?page=search&seller_post=' . osc_item_user_id();
  } else {
    $url = osc_base_url() . 'search/seller_post,' . osc_item_user_id() . '/iPage';
  }

  $user = User::newInstance()->findByPrimaryKey(osc_item_user_id());

  if ( osc_item_user_id() <> 0 ) {
    echo '<a id="inzerat_icohref" href="'. $url . '">';
    echo $user['i_items'] . ' ' . ($user['i_items'] == 1 ? __('item', 'list_seller_items') : __('items', 'list_seller_items'));
    echo '</a>';
  }
}
 
Выпадающие-категории-в-левой-колонке-поиска+доп.-параметры
- в functions.php в самый низ до ?> добавить
Код:

Код:
<!-- Side bar mouse-over category menu -->
function veronika_sidebar_category_search($catId = null)
{
$aCategories = array();
if($catId==null) {
    $aCategories[] = Category::newInstance()->findRootCategoriesEnabled();
} else {
    // if parent category, only show parent categories
    $aCategories = Category::newInstance()->toRootTree($catId);
    end($aCategories);
    $cat = current($aCategories);
    // if is parent of some category
    $childCategories = Category::newInstance()->findSubcategoriesEnabled($cat['pk_i_id']);
    if(count($childCategories) > 0) {
        $aCategories[] = $childCategories;
    }
}

if(count($aCategories) == 0) {
    return "";
}

veronika_print_sidebar_category_search($aCategories, $catId);
}

function veronika_print_sidebar_category_search($aCategories, $current_category = null, $i = 0)
{
$class = '';
if(!isset($aCategories[$i])) {
    return null;
}

if($i===0) {
    $class = 'class="list"';
}

$c   = $aCategories[$i];
$i++;
if(!isset($c['pk_i_id'])) {
    echo '<ul class="list">';
    if($i==1) {
        echo '<li class="option"><a href="'.osc_esc_html(osc_update_search_url(array('sCategory'=>null, 'iPage'=>null))).'"> ' . __('All categories', 'veronika')."</a></li>";
    }
    foreach($c as $key => $value) {
?>
<li class="option"> <a id="cat_<?php echo osc_esc_html($value['pk_i_id']);?>" href="<?php echo osc_esc_html(osc_update_search_url(array('sCategory'=> $value['pk_i_id'], 'iPage'=>null))); ?>">
<?php if(isset($current_category) && $current_category == $value['pk_i_id']){ echo '<span class="option bold selected">'.$value['s_name'].'</span>'; }
            else{ echo $value['s_name']; } ?>
</a> </li>
<?php
    }
    if($i==1) {
    echo "</ul>";
    } else {
    echo "</ul>";
    }
} else {
?>
<ul class="list">
<?php if($i==1) { ?>
<li class="option"><a href="<?php echo osc_esc_html(osc_update_search_url(array('sCategory'=>null, 'iPage'=>null))); ?>">
<?php _e('All categories', 'veronika'); ?>
</a></li>
<?php } ?>
<li class="option"><a id="cat_<?php echo osc_esc_html($c['pk_i_id']);?>" href="<?php echo osc_esc_html(osc_update_search_url(array('sCategory'=> $c['pk_i_id'], 'iPage'=>null))); ?>">
<?php if(isset($current_category) && $current_category == $c['pk_i_id']){ echo '<span class="option bold selected">'.$c['s_name'].'</span>'; }
                  else{ echo $c['s_name']; } ?>
</a>
<?php veronika_print_sidebar_category_search($aCategories, $current_category, $i); ?>
</li>
<?php if($i==1) { ?>
<?php } ?>
</ul>
<?php
}
}
<!-- Side bar mouse-over category menu konec -->

<!-- SUBKATEGORII-V-VUBRANNOI-KATEGORII-linkami -->
if( !function_exists('get_subcategories') ) {
         function get_subcategories( ) {
             $location = Rewrite::newInstance()->get_location() ;
             $section  = Rewrite::newInstance()->get_section() ;
            
             if ( $location != 'search' ) {
                 return false ;
             }
            
             $category_id = osc_search_category_id() ;
            
             if(count($category_id) > 1) {
                 return false ;
             }
            
             $category_id = (int) $category_id[0] ;
            
             $subCategories = Category::newInstance()->findSubcategories($category_id) ;
    
            
             foreach($subCategories as &$category) {
                 $category['url'] = get_category_url($category) ;
             }
            
             return $subCategories ;
         }
     }
      if ( !function_exists('get_category_url') ) {
         function get_category_url( $category ) {
             $path = '';
             if ( osc_rewrite_enabled() ) {
                if ($category != '') {
                    $category = Category::newInstance()->hierarchy($category['pk_i_id']) ;
                    $sanitized_category = "" ;
                    for ($i = count($category); $i > 0; $i--) {
                        $sanitized_category .= $category[$i - 1]['s_slug'] . '/' ;
                    }
                    $path = osc_base_url() . $sanitized_category ;
                }
            } else {
                $path = sprintf( osc_base_url(true) . '?page=search&sCategory=%d', $category['pk_i_id'] ) ;
            }
            
            return $path;
         }
     }
    
     if ( !function_exists('get_category_num_items') ) {
         function get_category_num_items( $category ) {
            $category_stats = CategoryStats::newInstance()->countItemsFromCategory($category['pk_i_id']) ;
            
            if( empty($category_stats) ) {
                return 0 ;
            }
            
            return $category_stats;
         }
     }
<!-- SUBKATEGORII-V-VUBRANNOI-KATEGORII-linkami-KONEC -->

- в search.php найти <fieldset class="box location"> и после него вставить
Код:

Код:
<?php
// раскомментировать код для показа под-категорий в mouse-over меню
/*$category = __get("category");
if(!isset($category['pk_i_id']) ) {
$category['pk_i_id'] = null;
}*/
?>

<!-- Side bar mouse-over category menu -->
<div class="input-box">
<div class="simple-condition simple-select">
<span class="text round3 tr1"><span><?php _e('Select a category', 'veronika') ; ?></span> <i class="fa fa-angle-down"></i></span>
<section>   
<?php veronika_sidebar_category_search($category['pk_i_id']); ?>

<?php $aCategories = osc_search_category();
foreach($aCategories as $cat_id) {
?>
<input type="hidden" name="sCategory[]" value="<?php echo osc_esc_html($cat_id); ?>"/>
<?php } ?>   </section>
</div>
</div>
<!-- Side bar mouse-over category menu -->

<!-- HOOCKS -->
<div class="sidebar-hooks">
<?php
GLOBAL $search_hooks;
ob_start(); // SAVE HTML
if(osc_search_category_id()) {
osc_run_hook('search_form', osc_search_category_id());
} else {
osc_run_hook('search_form');
}
//echo $search_hooks;
$search_hooks = ob_get_contents();   // CAPTURE HTML OF SIDEBAR HOOKS FOR FOOTER (MOBILE VIEW)
?>
</div>
<!-- HOOCKS -->

<!-- KATEGORII-VUBOR-PUTI-krohki -->

<?php
  // CURRENT CATEGORY
  $search_cat_id = osc_search_category_id();
  $search_cat_id = isset($search_cat_id[0]) ? $search_cat_id[0] : 0;
  $search_cat_full = Category::newInstance()->findByPrimaryKey($search_cat_id);

  // ROOT CATEGORY
  $root_cat_id = Category::newInstance()->findRootCategory($search_cat_id);
  $root_cat_id = $root_cat_id['pk_i_id'];
  
  // HIERARCHY OF SEARCH CATEGORY
  $hierarchy = Category::newInstance()->toRootTree($search_cat_id);

  // SUBCATEGORIES OF SEARCH CATEGORY
  $subcats = Category::newInstance()->findSubcategories($search_cat_id);

  if(empty($subcats)) {
    $is_subcat = false;
    $subcats = Category::newInstance()->findSubcategories($search_cat_full['fk_i_parent_id']);
  } else {
    $is_subcat = true;
  }
?>
            <div class="cat-navigation">
              <?php
                unset($search_params['sCategory']);
                echo '<a id="cat-link" href="' . osc_search_url($search_params) . '">' . __('All categories', 'veronika') . '</a>';

                foreach($hierarchy as $h) {
                  $search_params['sCategory'] = $h['pk_i_id'];
                  echo '<a id="cat-link" href="' . osc_search_url($search_params) . '">' . $h['s_name'] . '</a>';
                }
              ?>
            </div>

<!-- KATEGORII-VUBOR-PUTI-KONEC -->

<!-- SUBKATEGORII-V-VUBRANNOI-KATEGORII-linkami -->
<div id="cat-link">   
<ul>
<li>
<?php foreach(get_subcategories() as $subcat) { echo "<a href='".$subcat["url"]."'>".$subcat["s_name"]."</a> <span>(".get_category_num_items($subcat).")</span> | " ; } ?>
</li>
</ul>
</div>
<!-- SUBKATEGORII-V-VUBRANNOI-KATEGORII-linkami-KONEC -->
 
Реализация поиска по части слова, а не целиком + поиск объявлений используя юзера по имени
В файл темы function.php в самом низу добавим код

Код:
function search_wildcard_usrname($params) {

    if (@$params['sPattern']) {
        $mSearch =  Search::newInstance();
        $query_elements = (array) json_decode($mSearch->toJson());
        $pattern = $query_elements['sPattern'];
        $query_elements['sPattern'] = str_replace(' ', '* ', $pattern) . '*';
        $mSearch->setJsonAlert($query_elements);

        // username search
        $aPattern = explode(' ', $pattern);
        $userNameCond = '';

        foreach ($aPattern as $word) {
            if ($word) $userNameCond .= sprintf(" || %st_item.s_contact_name LIKE '%s%%'", DB_TABLE_PREFIX, $word);
        }

        $mSearch->addConditions("1 = 1 " . $userNameCond);
        $mSearch->addGroupBy(DB_TABLE_PREFIX.'t_item.pk_i_id');
    }
}

osc_add_hook('search_conditions', 'search_wildcard_usrname', 1);

1. Теперь если искомое слово в объявлении ПРИВЕТ search engine будет находить слово ПРИ (ПРИвет, ПРИтирка и т.д.)
2. Можно найти все объявления юзера в котором содержится username ЕЛЕНА
 
Plugin User Rating Plugin

в админке:
1. добавим последний IP юзера
2. e-mail кому конкретно была дана оценка
3. линк на е-mail - a вдруг это злостный продавец и обманщик ? ) (сразу в бан)




1. user_rating/style/admin.css //уменьшим размер столбца, что бы оставить место для столбика e-mail
найдем
Код:
.mb-col-8 {width:33.33333%}
Код:
.mb-col-8 {width:16.66665%}

2. user_rating/admin/rating.php
меняем на
rating.php
Код:
<?php
  // Create menu
  $title = __('Ratings', 'user_rating');
  ur_menu($title);

  $validate = osc_get_preference('validate', 'plugin-user_rating');


  // VALIDATE LISTINGS
  if( Params::getParam('plugin_action') == 'validate' ) {

    // APPROVE SINGLE
    $params_array = Params::getParamsAsArray();

    $approved = '';
    foreach($params_array as $key => $value){
      $exp_key = explode('_', $key);
      if($exp_key[0] == 'approve-single'){
        // ID of prompted rating stored in $value
        $approved .= $exp_key[1] . ', ';
        message_ok( __('Rating(s) with following IDs were approved:', 'user_rating') . ' ' .  substr($approved, 0, strlen($approved)-2));

        ModelUR::newInstance()->validateRatingById( $exp_key[1] );
      }
    }



    // REMOVE SINGLE
    $params_array = Params::getParamsAsArray();

    $removed = '';
    foreach($params_array as $key => $value){
      $exp_key = explode('_', $key);
      if($exp_key[0] == 'remove-single'){
        // ID of prompted rating stored in $value
        $removed .= $exp_key[1] . ', ';
        message_ok( __('Rating(s) with following IDs were removed:', 'user_rating') . ' ' .  substr($removed, 0, strlen($removed)-2));

        ModelUR::newInstance()->removeRatingById( $exp_key[1] );
      }
    }



    // APPROVE SELECTED
    if( Params::getParam('item_action') == __('Approve Selected', 'user_rating') ) {
      $params_array = Params::getParamsAsArray();

      if( is_array($params_array) && !empty($params_array) ) {
        $approved = '';
        foreach($params_array as $key => $value){
          $exp_key = explode('_', $key);
          if($exp_key[0] == 'valid'){
            // ID of prompted ratings stored in $value
            $approved .= $value . ', ';

            ModelUR::newInstance()->validateRatingById( $exp_key[1] );

          }
        }
      }

      message_ok( __('Rating(s) with following IDs were approved:', 'user_rating') . ' ' .  substr($approved, 0, strlen($approved)-2));
    }



    // REMOVE SELECTED
    if( Params::getParam('item_action') == __('Remove Selected', 'user_rating') ) {
      $params_array = Params::getParamsAsArray();

      if( is_array($params_array) && !empty($params_array) ) {
        $removed = '';
        foreach($params_array as $key => $value){
          $exp_key = explode('_', $key);
          if($exp_key[0] == 'valid'){
            // ID of prompted ratings stored in $value
            $removed .= $value . ', ';

            ModelUR::newInstance()->removeRatingById( $exp_key[1] );
          }
        }
      }

      message_ok( __('Rating(s) with following IDs were removed:', 'user_rating') . ' ' .  substr($removed, 0, strlen($removed)-2));
    }
  }
?>



<div class="mb-body">

  <!-- TO BE VALIDATED SECTION -->
  <?php if($validate == 1) { ?>
    <div class="mb-box">
      <div class="mb-head"><i class="fa fa-stack-overflow"></i> <?php _e('Ratings to be Validated', 'user_rating'); ?></div>

      <div class="mb-inside">
        <form name="promo_form" id="promo_form" action="<?php echo osc_admin_base_url(true); ?>" method="POST" enctype="multipart/form-data" >
          <input type="hidden" name="page" value="plugins" />
          <input type="hidden" name="action" value="renderplugin" />
          <input type="hidden" name="file" value="<?php echo osc_plugin_folder(__FILE__); ?>rating.php" />
          <input type="hidden" name="plugin_action" value="validate" />


          <?php $ratings = ModelUR::newInstance()->getAllRatings(2, 100); ?>


          <?php if(count($ratings) > 0) { ?>
            <div class="mb-info-box" style="margin-top:20px;margin-bottom:25px;">
              <div class="mb-line"><?php _e('Only latest 100 ratings are shown!', 'user_rating'); ?></div>
            </div>

            <div class="mb-table" style="margin-bottom:30px;">
              <div class="mb-table-head">
                <div class="mb-col-1"><input type="checkbox" class="mb_mark_all" name="mb_mark_all" id="mb_mark_all" value="valid_" /></div>
                <div class="mb-col-1"><?php _e('ID', 'user_rating'); ?></div>
                <div class="mb-col-3"><?php _e('Rating', 'user_rating'); ?></div>
                <div class="mb-col-2"><?php _e('User', 'user_rating'); ?></div>
                <div class="mb-col-3"><?php _e('Type', 'user_rating'); ?></div>
                <div class="mb-col-8 mb-align-left"><?php _e('Comment', 'user_rating'); ?></div>
                <div class="mb-col-2"><?php _e('Status', 'user_rating'); ?></div>
                <div class="mb-col-4 mb-align-left">&nbsp;</div>
              </div>


              <?php foreach( $ratings as $r ) { ?>
                <?php
                  if($r['fk_i_user_id'] <> 0 && $r['fk_i_user_id'] <> '') {

                    $user = User::newInstance()->findByPrimaryKey($r['fk_i_user_id']);
                    $user_name = $user['s_name'] . ' (' . $user['s_email'] . ')';
                    $user_type = __('Registered', 'user_rating');
                  } else {
                    $user_name = $r['s_user_email'];
                    $user_type = __('Unregistered', 'user_rating');
                  }

                  if($r['fk_i_from_user_id'] <> 0 && $r['fk_i_from_user_id'] <> '') {
                    $from_user = User::newInstance()->findByPrimaryKey($r['fk_i_from_user_id']);
                    $from_user_name = $from_user['s_name'] . ' (' . $from_user['s_email'] . ')';
                    $from_user_type = __('Registered', 'user_rating');
                  } else {
                    $from_user_name = __('Unknown', 'user_rating');
                    $from_user_type = __('Unregistered', 'user_rating');
                  }

                  $user_title = __('Rated user', 'user_rating') . '<br />';
                  $user_title .= __('Name', 'user_rating') . ': ' . $user_name . '<br />';
                  $user_title .= __('Type', 'user_rating') . ': ' . $user_type . '<br /><br />';
                  $user_title .= __('Rating left by', 'user_rating') . '<br />';
                  $user_title .= __('Name', 'user_rating') . ': ' . $from_user_name . '<br />';
                  $user_title .= __('Type', 'user_rating') . ': ' . $from_user_type . '<br /><br />';
                  $user_title .= __('Date', 'user_rating') . ': ' . $r['d_datetime'];

                  $status = $r['i_validate'];
                  $status_name = '';
                  $status_class = '';

                  if($status == 0) {
                    $status_name = __('Pending', 'user_rating');
                    $status_class = 'mb-blue';
                  } else if ($status == 1) {
                    $status_name = __('Valid', 'user_rating');
                    $status_class = 'mb-green';
                  }

                  $empty = '<span class="mb-i mb-gray">' . __('No comment', 'user_rating') . '</span>';

                  $avg = ModelUR::newInstance()->getRatingAverageByRatingId($r['i_rating_id']);
                  $color = ur_user_color($avg);
                ?>

                <div class="mb-table-row">
                  <div class="mb-col-1 <?php echo osc_esc_html($status_class); ?>" title="<?php echo osc_esc_html($status_name); ?>"><input type="checkbox" name="valid_<?php echo $r['i_rating_id']; ?>" id="valid_<?php echo $r['i_rating_id']; ?>" value="<?php echo $r['i_rating_id']; ?>" /></div>
                  <div class="mb-col-1"><?php echo $r['i_rating_id']; ?></div>
                  <div class="mb-col-3 mb-stars <?php echo $color; ?>"><?php echo ur_get_stars($avg); ?></div>
                  <div class="mb-col-2 mb-has-tooltip-user" title="<?php echo osc_esc_html($user_title); ?>"><i class="fa fa-user from"></i> <i class="fa fa-long-arrow-right"></i> <i class="fa fa-user to"></i></div>
                  <div class="mb-col-3"><?php echo $r['i_type'] == 0 ? __('Buyer rated Seller', 'user_rating') : __('Seller rated Buyer', 'user_rating'); ?></div>
                  <div class="mb-col-8 mb-align-left mb-no-wrap" title="<?php echo osc_esc_html($r['s_comment']); ?>"><?php echo trim($r['s_comment']) <> '' ? $r['s_comment'] : $empty; ?></div>
                  <div class="mb-col-2"><?php echo $status_name; ?></div>
                  <div class="mb-col-4 mb-align-left">
                    <input type="submit" name="approve-single_<?php echo $r['i_rating_id']; ?>" class="mb-button-green" style="float:left;margin: -3px 0; height: 27px; line-height: 13px;" value="<?php echo osc_esc_html(__('Approve', 'user_rating')); ?>"/>
                    <input type="submit" name="remove-single_<?php echo $r['i_rating_id']; ?>" class="mb-button-red" style="float:left;margin: -3px 0 -3px 6px; height: 27px; line-height: 13px;" value="<?php echo osc_esc_html(__('Remove', 'user_rating')); ?>" onclick="return confirm('<?php echo osc_esc_js(__('Are you sure you want to remove this rating? Action cannot be undone', 'user_rating')); ?>?')" />
                  </div>
                </div>
              <?php } ?>
            </div>

            <div class="mb-foot">
              <input type="submit" name="item_action" class="mb-button-white" style="float:left;margin-right:10px;" value="<?php echo osc_esc_html(__('Approve Selected', 'user_rating')); ?>" />
              <input type="submit" name="item_action" class="mb-button-white" style="float:left" value="<?php echo osc_esc_html(__('Remove Selected', 'user_rating')); ?>" onclick="return confirm('<?php echo osc_esc_js(__('Are you sure you want to remove selected ratings? Action cannot be undone', 'user_rating')); ?>?')" />
            </div>

          <?php } else { ?>
            <div class="mb-info-box" style="margin-top:20px;margin-bottom:25px;">
              <div class="mb-line"><?php _e('No ratings waiting for validation', 'user_rating'); ?></div>
            </div>
          <?php } ?>
        </div>
      </form>
    </div>
  <?php } ?>



  <!-- VALIDATED SECTION -->
  <div class="mb-box">
    <div class="mb-head"><i class="fa fa-check-circle"></i> <?php _e('Validated Ratings', 'user_rating'); ?></div>

    <div class="mb-inside">
      <form name="promo_form" id="promo_form" action="<?php echo osc_admin_base_url(true); ?>" method="POST" enctype="multipart/form-data" >
        <input type="hidden" name="page" value="plugins" />
        <input type="hidden" name="action" value="renderplugin" />
        <input type="hidden" name="file" value="<?php echo osc_plugin_folder(__FILE__); ?>rating.php" />
        <input type="hidden" name="plugin_action" value="validate" />


        <?php $ratings = ModelUR::newInstance()->getAllRatings($validate, 100); ?>


        <?php if(count($ratings) > 0) { ?>
          <div class="mb-info-box" style="margin-top:20px;margin-bottom:25px;">
            <div class="mb-line"><?php _e('Only latest 100 ratings are shown!', 'user_rating'); ?></div>
          </div>

          <div class="mb-table" style="margin-bottom:30px;">
            <div class="mb-table-head">
              <div class="mb-col-1"><input type="checkbox" class="mb_mark_all" name="mb_mark_all" id="mb_mark_all" value="valid_" /></div>
              <div class="mb-col-1"><?php _e('ID', 'user_rating'); ?></div>
              <div class="mb-col-3"><?php _e('Rating', 'user_rating'); ?></div>
              <div class="mb-col-2"><?php _e('User', 'user_rating'); ?></div>
              <div class="mb-col-3"><?php _e('Type', 'user_rating'); ?></div>
              <div class="mb-col-8 mb-align-left"><?php _e('Comment', 'user_rating'); ?></div>
              <!--mod sz add e-mail title -->
              <div class="mb-col-8 mb-align-left"><?php _e('e-mail', 'user_rating'); ?></div>
              <!--mod sz add e-mail title -->
              <div class="mb-col-2"><?php _e('Status', 'user_rating'); ?></div>
              <div class="mb-col-4 mb-align-left">&nbsp;</div>
            </div>


            <?php foreach( $ratings as $r ) { ?>
              <?php
       
     
                if($r['fk_i_user_id'] <> 0 && $r['fk_i_user_id'] <> '') {
                  $user = User::newInstance()->findByPrimaryKey($r['fk_i_user_id']);
             
             
                  $user_name = $user['s_name'] . ' (' . $user['s_email'] . ')';
                  $user_type = __('Registered', 'user_rating');
                } else {
                  $user_name = $r['s_user_email'];
                  $user_type = __('Unregistered', 'user_rating');
                }

                if($r['fk_i_from_user_id'] <> 0 && $r['fk_i_from_user_id'] <> '') {
                  $from_user = User::newInstance()->findByPrimaryKey($r['fk_i_from_user_id']);
                  $from_user_name = $user['s_name'] . ' (' . $user['s_email'] . ')';
                  $from_user_type = __('Registered', 'user_rating');
                } else {
                  $from_user_name = __('Unknown', 'user_rating');
                  $from_user_type = __('Unregistered', 'user_rating');
                }

                $user_title = __('Rated user', 'user_rating') . '<br />';
                $user_title .= __('Name', 'user_rating') . ': ' . $user_name . '<br />';
                $user_title .= __('Type', 'user_rating') . ': ' . $user_type . '<br /><br />';
                $user_title .= __('Rating left by', 'user_rating') . '<br />';
                $user_title .= __('Name', 'user_rating') . ': ' . $from_user_name . '<br />';
                $user_title .= __('Type', 'user_rating') . ': ' . $from_user_type . '<br /><br />';
                $user_title .= __('Date', 'user_rating') . ': ' . $r['d_datetime'];


                $status = $r['i_validate'];
                $status_name = '';
                $status_class = '';

                if($status == 0) {
                  if($validate == 1) {
                    $status_name = __('Pending', 'user_rating');
                    $status_class = 'mb-blue';
                  } else {
                    $status_name = __('Valid', 'user_rating');
                    $status_class = 'mb-green';
                  }
                } else if ($status == 1) {
                  $status_name = __('Valid', 'user_rating');
                  $status_class = 'mb-green';
                }

                $empty = '<span class="mb-i mb-gray">' . __('No comment', 'user_rating') . '</span>';

                $avg = ModelUR::newInstance()->getRatingAverageByRatingId($r['i_rating_id']);
                $color = ur_user_color($avg);
              ?>

              <div class="mb-table-row">
                <div class="mb-col-1 <?php echo osc_esc_html($status_class); ?>" title="<?php echo osc_esc_html($status_name); ?>"><input type="checkbox" name="valid_<?php echo $r['i_rating_id']; ?>" id="valid_<?php echo $r['i_rating_id']; ?>" value="<?php echo $r['i_rating_id']; ?>" /></div>

                <div class="mb-col-1"><?php echo $r['i_rating_id']; ?></div>
                <div class="mb-col-3 mb-stars <?php echo $color; ?>"><?php echo ur_get_stars($avg); ?></div>
                <div class="mb-col-2 mb-has-tooltip-user" title="<?php echo $user_title; ?>"><i class="fa fa-user from"></i> <i class="fa fa-long-arrow-right"></i> <i class="fa fa-user to"></i>
                  <!--mod sz add IP -->
                <div><?php echo $user['s_access_ip']; ?></div>
                  <!--mod sz add IP -->
                </div>
                <div class="mb-col-3"><?php echo $r['i_type'] == 0 ? __('Buyer rated Seller', 'user_rating') : __('Seller rated Buyer', 'user_rating'); ?></div>
                <div class="mb-col-8 mb-align-left mb-no-wrap" title="<?php echo $r['s_comment']; ?>""><?php echo trim($r['s_comment']) <> '' ? $r['s_comment'] : $empty; ?></div>
               <!--mod sz add column with mail -->
               <div class="mb-col-8 mb-align-left mb-no-wrap">
                <a href="<?php echo osc_admin_base_url(true); ?>?page=users&action=edit&id=<?php echo $r['fk_i_user_id']; ?>"> <?php echo $user['s_email'] ?></a></div>
               <!--mod sz add column with mail -->

                <div class="mb-col-2"><?php echo $status_name; ?></div>
                <div class="mb-col-4 mb-align-left">
                  <input type="submit" name="remove-single_<?php echo $r['i_rating_id']; ?>" class="mb-button-red" style="float:left;margin: -3px 0; height: 27px; line-height: 13px;" value="<?php echo osc_esc_html(__('Remove', 'user_rating')); ?>" onclick="return confirm('<?php echo osc_esc_js(__('Are you sure you want to remove this rating? Action cannot be undone', 'user_rating')); ?>?')" />
                </div>
              </div>
            <?php } ?>
          </div>

          <div class="mb-foot">
            <input type="submit" name="item_action" class="mb-button-white" style="float:left" value="<?php echo osc_esc_html(__('Remove Selected', 'user_rating')); ?>" onclick="return confirm('<?php echo osc_esc_js(__('Are you sure you want to remove selected ratings? Action cannot be undone', 'user_rating')); ?>?')" />
          </div>

        <?php } else { ?>
          <div class="mb-info-box" style="margin-top:20px;margin-bottom:25px;">
            <div class="mb-line"><?php _e('No validated ratings yet', 'user_rating'); ?></div>
          </div>
        <?php } ?>
      </div>
    </form>
  </div>
</div>

<?php echo ur_footer(); ?>
все изменения помечены
Код:
  <!--mod sz ... -->
 

Вложения

  • Screen Shot 2022-01-15 at 9.06.16 AM.png
    Screen Shot 2022-01-15 at 9.06.16 AM.png
    218,1 КБ · Просмотры: 2
  • Screen Shot 2022-01-15 at 9.06.09 AM.png
    Screen Shot 2022-01-15 at 9.06.09 AM.png
    254,3 КБ · Просмотры: 2
Реализация push notification для вашего андроида
используем гугля конечно, доки тут :
https://firebase.google.com/docs/cloud-messaging/

PHP функция
Код:
function sz_push_notification(){

    $token = ''; // Topic or Token devices here
    $serverKey = ''; // add api key here


    $url = "https://fcm.googleapis.com/fcm/send";
    //item details
    $item_title = osc_highlight(strip_tags(osc_item_title()), 50);
    $item_description = osc_highlight(strip_tags(osc_item_description()), 100);
    if(osc_count_item_resources() > 0) {
        $image = osc_resource_thumbnail_url();
    } else {
        $image = osc_current_web_theme_url('images/mob_logo.png');
    }

    $notification = array('title' => $item_title , 'body' => $item_description, 'sound' => 'default', 'badge' => '1', 'image' =>$image);
    $itemUrl = array('extra_information'=>osc_item_url());
    $arrayToSend = array('to' => $token,'data'=>$itemUrl, 'notification' => $notification, 'priority'=>'high');
    $json = json_encode($arrayToSend);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key='. $serverKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);

    //Send the request
    $response = curl_exec($ch);
    //Close request
    if ($response === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
}
osc_add_hook("posted_item","sz_push_notification");
Class для Андройда
Код:
public class FcmMessagingService extends FirebaseMessagingService {

    String type = "", remoteURLpassedJson;
    SharedPreferences sharedpreferences;
    public static final String NOTIFICATION_CHANNEL_ID = "10001";


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        //Topic string from curl request (/topics/news)
        Map<String, String> data = remoteMessage.getData();
        //pass URL from json - extra_information
        remoteURLpassedJson = data.get("extra_information");
        Log.d(TAG, "jsonURLremoteMesg: " + remoteURLpassedJson);
 
        if (remoteMessage.getData().size() > 0) {
            type = "json";
            sendNotification(remoteMessage.getData().toString());
            Log.d(TAG, "FromSZ: " + remoteMessage.getData());

        }
        if (remoteMessage.getNotification() !=null) {
            type = "message";
            sendNotification(remoteMessage.getNotification().getBody());
            Log.d("getData", "onMessageReceived: " +  remoteMessage.getData());
        }
    }
    private void sendNotification(String messageBody){

        String id="",message="",title="";

        if(type.equals("json")) {
            try {
                JSONObject jsonObject = new JSONObject(messageBody);
                id = jsonObject.getString("id");
                Log.d("id", "message " + id.toString());
                message = jsonObject.getString("message");
                Log.d("message", "message " + message.toString());
                title = jsonObject.getString("title");

            } catch (JSONException e) {
                //            }
            }
        }
        else if(type.equals("message"))
        {
            message = messageBody;

        }

        Intent intent=new Intent(this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("message", message);// Add more data as per need
        //pass message via broadcast
        Intent intent2 = new Intent("com.push.message.received");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent2.putExtra("remoteURLpassedJson", remoteURLpassedJson);// Add more data as per need passed DATA URL
        sendBroadcast(intent2);
        sharedpreferences = getApplicationContext().getSharedPreferences("mypref", 0); // 0 - for private mode
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.clear();
        editor.putString("mypref", message);
        editor.commit();

        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
        notificationBuilder.setContentTitle(getString(R.string.app_name));
        notificationBuilder.setContentText(message);
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        notificationBuilder.setSound(soundUri);
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_launcher));
        notificationBuilder.setAutoCancel(true);
        Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(1000);
        notificationBuilder.setContentIntent(pendingIntent);
        NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Log.d("Hi", "Passed data " );
        Log.d("getData", "onMessageReceived: " );

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
        {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);

            notificationBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            notificationManager.createNotificationChannel(notificationChannel);
        }


        Log.d("biuld", "build" );
       notificationManager.notify(0,notificationBuilder.build());
    }


}

Testing Video
 
Последнее редактирование:
Если надоело переводить плагины сторонними прогами, то можно это делать сразу на сервере, а желательно с админки.
Идея в том - что бы закомпилить МО файл с переведенного ПО файла.
Вот собственно и код:
Код:
<?php
/**
* Created by PhpStorm.
* User: safeacid
* Date: 2020-12-26
* Time: 18:24
*/

/**
* php.mo 0.1 by Joss Crowcroft (http://www.josscrowcroft.com)
*
* Converts gettext translation '.po' files to binary '.mo' files in PHP.
*
* Usage:
* <?php require('php-mo.php'); phpmo_convert( 'input.po', [ 'output.mo' ] ); ?>
*
* NB:
* - If no $output_file specified, output filename is same as $input_file (but .mo)
* - Returns true/false for success/failure
* - No warranty, but if it breaks, please let me know
*
* More info:
* https://github.com/josscrowcroft/php.mo
*
* Based on php-msgfmt by Matthias Bauer (Copyright © 2007), a command-line PHP tool
* for converting .po files to .mo.
* (http://wordpress-soc-2007.googlecode.com/svn/trunk/moeffju/php-msgfmt/msgfmt.php)
*
* License: GPL v3 http://www.opensource.org/licenses/gpl-3.0.html
*/

/**
* The main .po to .mo function
*/
function phpmo_convert($input, $output = false) {
    if ( !$output )
        $output = str_replace( '.po', '.mo', $input );

    $hash = phpmo_parse_po_file( $input );
    if ( $hash === false ) {
        return false;
    } else {
        phpmo_write_mo_file( $hash, $output );
        return true;
    }
}

function phpmo_clean_helper($x) {
    if (is_array($x)) {
        foreach ($x as $k => $v) {
            $x[$k] = phpmo_clean_helper($v);
        }
    } else {
        if ($x[0] == '"')
            $x = substr($x, 1, -1);
        $x = str_replace("\"\n\"", '', $x);
        $x = str_replace('$', '\\$', $x);
    }
    return $x;
}

/* Parse gettext .po files. */
/* @link http://www.gnu.org/software/gettext/manual/gettext.html#PO-Files */
function phpmo_parse_po_file($in) {
// read .po file
    $fh = fopen($in, 'r');
    if ($fh === false) {
// Could not open file resource
        return false;
    }

// results array
    $hash = array ();
// temporary array
    $temp = array ();
// state
    $state = null;
    $fuzzy = false;

// iterate over lines
    while(($line = fgets($fh, 65536)) !== false) {
        $line = trim($line);
        if ($line === '')
            continue;

        list ($key, $data) = preg_split('/\s/', $line, 2);

        switch ($key) {
            case '#,' : // flag...
                $fuzzy = in_array('fuzzy', preg_split('/,\s*/', $data));
            case '#' : // translator-comments
            case '#.' : // extracted-comments
            case '#:' : // reference...
            case '#|' : // msgid previous-untranslated-string
// start a new entry
                if (sizeof($temp) && array_key_exists('msgid', $temp) && array_key_exists('msgstr', $temp)) {
                    if (!$fuzzy)
                        $hash[] = $temp;
                    $temp = array ();
                    $state = null;
                    $fuzzy = false;
                }
                break;
            case 'msgctxt' :
// context
            case 'msgid' :
// untranslated-string
            case 'msgid_plural' :
// untranslated-string-plural
                $state = $key;
                $temp[$state] = $data;
                break;
            case 'msgstr' :
// translated-string
                $state = 'msgstr';
                $temp[$state][] = $data;
                break;
            default :
                if (strpos($key, 'msgstr[') !== FALSE) {
// translated-string-case-n
                    $state = 'msgstr';
                    $temp[$state][] = $data;
                } else {
// continued lines
                    switch ($state) {
                        case 'msgctxt' :
                        case 'msgid' :
                        case 'msgid_plural' :
                            $temp[$state] .= "\n" . $line;
                            break;
                        case 'msgstr' :
                            $temp[$state][sizeof($temp[$state]) - 1] .= "\n" . $line;
                            break;
                        default :
// parse error
                            fclose($fh);
                            return FALSE;
                    }
                }
                break;
        }
    }
    fclose($fh);

// add final entry
    if ($state == 'msgstr')
        $hash[] = $temp;

// Cleanup data, merge multiline entries, reindex hash for ksort
    $temp = $hash;
    $hash = array ();
    foreach ($temp as $entry) {
        foreach ($entry as & $v) {
            $v = phpmo_clean_helper($v);
            if ($v === FALSE) {
// parse error
                return FALSE;
            }
        }
        $hash[$entry['msgid']] = $entry;
    }

    return $hash;
}

/* Write a GNU gettext style machine object. */
/* @link http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files */
function phpmo_write_mo_file($hash, $out) {
// sort by msgid
    ksort($hash, SORT_STRING);
// our mo file data
    $mo = '';
// header data
    $offsets = array ();
    $ids = '';
    $strings = '';

    foreach ($hash as $entry) {
        $id = $entry['msgid'];
        if (isset ($entry['msgid_plural']))
            $id .= "\x00" . $entry['msgid_plural'];
// context is merged into id, separated by EOT (\x04)
        if (array_key_exists('msgctxt', $entry))
            $id = $entry['msgctxt'] . "\x04" . $id;
// plural msgstrs are NUL-separated
        $str = implode("\x00", $entry['msgstr']);
// keep track of offsets
        $offsets[] = array (
            strlen($ids
            ), strlen($id), strlen($strings), strlen($str));
// plural msgids are not stored (?)
        $ids .= $id . "\x00";
        $strings .= $str . "\x00";
    }

// keys start after the header (7 words) + index tables ($#hash * 4 words)
    $key_start = 7 * 4 + sizeof($hash) * 4 * 4;
// values start right after the keys
    $value_start = $key_start +strlen($ids);
// first all key offsets, then all value offsets
    $key_offsets = array ();
    $value_offsets = array ();
// calculate
    foreach ($offsets as $v) {
        list ($o1, $l1, $o2, $l2) = $v;
        $key_offsets[] = $l1;
        $key_offsets[] = $o1 + $key_start;
        $value_offsets[] = $l2;
        $value_offsets[] = $o2 + $value_start;
    }
    $offsets = array_merge($key_offsets, $value_offsets);

// write header
    $mo .= pack('Iiiiiii', 0x950412de, // magic number
        0, // version
        sizeof($hash), // number of entries in the catalog
        7 * 4, // key index offset
        7 * 4 + sizeof($hash) * 8, // value index offset,
        0, // hashtable size (unused, thus 0)
        $key_start // hashtable offset
    );
// offsets
    foreach ($offsets as $offset)
        $mo .= pack('i', $offset);
// ids
    $mo .= $ids;
// strings
    $mo .= $strings;

    file_put_contents($out, $mo);
}

?>
Если вас одолеет лень, то можно взять тут.
 
WhatsApp Chat кнопка на странице объявления:

1. Для реализации понадобится 2 файла, библиотеки, загруженные в тему
../yourTheme/css/floating-wpp.min.css
../yourTheme/js/floating-wpp.js

2. Подключим библиотеку через head.php вашей темы
Код:
    <!--mod sz whatsApp library-->
<?php if (osc_is_ad_page()) { ?>
    <link rel="stylesheet" href="<?php echo osc_current_web_theme_url('css/floating-wpp.min.css'); ?>">
    <?php
    osc_register_script('sz_whatsApp', osc_current_web_theme_js_url('floating-wpp.min.js'));
    osc_enqueue_script('sz_whatsApp');
} ?>

3. В item.php закинем кнопочку (любое место)
Код:
<div id="kot_whatsAppBtn"></div>
4. В item.php в самом низу инициализируем и вызовем функцию JS (все доступные свойства библиотеки указанные в комментарии)
<script>
$(document).ready(function(){
$(function() {
$('#kot_whatsAppBtn').floatingWhatsApp({
phone: sz_whatsAppPhone,
size:"50px",
headerTitle:'<?php osc_esc_js(_e('Write to author via WhatsApp', 'violet')); ?>',
popupMessage: '<?php osc_esc_js(_e('Please inform the author that classified has been found on osc4u.com', 'violet')); ?>',
showPopup: true,
zIndex: 777,
position: "right"
//available pre-set js properties
//size: "72px", backgroundColor: "#25D366", position: "left", popupMessage: "", showPopup: !1, showOnIE: !0, autoOpenTimeout: 0, headerColor: "#128C7E", headerTitle: "WhatsApp Chat", zIndex: 0,
});
});

});

</script>
5. Обратим на вышеуказанную строчку и переменную sz_whatsAppPhone в JS коде
Код:
phone: sz_whatsAppPhone,
тут вам надо присвоить телефон из объявления через PHP, как пример это можно объявить в item.php
Код:
<script>
let sz_whatsAppPhone = '<?php echo osc_esc_js(ITEM_PHONE_HERE); ?>';
</script>


6. Наслаждаемся :)

Библиотеки
floating-wpp.min.js.zip
floating-wpp.min.css.zip
 

Вложения

  • Screen Shot 2022-01-15 at 9.18.47 AM.png
    Screen Shot 2022-01-15 at 9.18.47 AM.png
    586,9 КБ · Просмотры: 3
  • Screen Shot 2022-01-15 at 9.18.33 AM.png
    Screen Shot 2022-01-15 at 9.18.33 AM.png
    684,5 КБ · Просмотры: 3
  • Screen Shot 2022-01-15 at 9.18.18 AM.png
    Screen Shot 2022-01-15 at 9.18.18 AM.png
    42,9 КБ · Просмотры: 3
Если надоело переводить плагины сторонними прогами, то можно это делать сразу на сервере, а желательно с админки.
Идея в том - что бы закомпилить МО файл с переведенного ПО файла.
Вот собственно и код:
Код:
<?php
/**
* Created by PhpStorm.
* User: safeacid
* Date: 2020-12-26
* Time: 18:24
*/

/**
* php.mo 0.1 by Joss Crowcroft (http://www.josscrowcroft.com)
*
* Converts gettext translation '.po' files to binary '.mo' files in PHP.
*
* Usage:
* <?php require('php-mo.php'); phpmo_convert( 'input.po', [ 'output.mo' ] ); ?>
*
* NB:
* - If no $output_file specified, output filename is same as $input_file (but .mo)
* - Returns true/false for success/failure
* - No warranty, but if it breaks, please let me know
*
* More info:
* https://github.com/josscrowcroft/php.mo
*
* Based on php-msgfmt by Matthias Bauer (Copyright © 2007), a command-line PHP tool
* for converting .po files to .mo.
* (http://wordpress-soc-2007.googlecode.com/svn/trunk/moeffju/php-msgfmt/msgfmt.php)
*
* License: GPL v3 http://www.opensource.org/licenses/gpl-3.0.html
*/

/**
* The main .po to .mo function
*/
function phpmo_convert($input, $output = false) {
    if ( !$output )
        $output = str_replace( '.po', '.mo', $input );

    $hash = phpmo_parse_po_file( $input );
    if ( $hash === false ) {
        return false;
    } else {
        phpmo_write_mo_file( $hash, $output );
        return true;
    }
}

function phpmo_clean_helper($x) {
    if (is_array($x)) {
        foreach ($x as $k => $v) {
            $x[$k] = phpmo_clean_helper($v);
        }
    } else {
        if ($x[0] == '"')
            $x = substr($x, 1, -1);
        $x = str_replace("\"\n\"", '', $x);
        $x = str_replace('$', '\\$', $x);
    }
    return $x;
}

/* Parse gettext .po files. */
/* @link http://www.gnu.org/software/gettext/manual/gettext.html#PO-Files */
function phpmo_parse_po_file($in) {
// read .po file
    $fh = fopen($in, 'r');
    if ($fh === false) {
// Could not open file resource
        return false;
    }

// results array
    $hash = array ();
// temporary array
    $temp = array ();
// state
    $state = null;
    $fuzzy = false;

// iterate over lines
    while(($line = fgets($fh, 65536)) !== false) {
        $line = trim($line);
        if ($line === '')
            continue;

        list ($key, $data) = preg_split('/\s/', $line, 2);

        switch ($key) {
            case '#,' : // flag...
                $fuzzy = in_array('fuzzy', preg_split('/,\s*/', $data));
            case '#' : // translator-comments
            case '#.' : // extracted-comments
            case '#:' : // reference...
            case '#|' : // msgid previous-untranslated-string
// start a new entry
                if (sizeof($temp) && array_key_exists('msgid', $temp) && array_key_exists('msgstr', $temp)) {
                    if (!$fuzzy)
                        $hash[] = $temp;
                    $temp = array ();
                    $state = null;
                    $fuzzy = false;
                }
                break;
            case 'msgctxt' :
// context
            case 'msgid' :
// untranslated-string
            case 'msgid_plural' :
// untranslated-string-plural
                $state = $key;
                $temp[$state] = $data;
                break;
            case 'msgstr' :
// translated-string
                $state = 'msgstr';
                $temp[$state][] = $data;
                break;
            default :
                if (strpos($key, 'msgstr[') !== FALSE) {
// translated-string-case-n
                    $state = 'msgstr';
                    $temp[$state][] = $data;
                } else {
// continued lines
                    switch ($state) {
                        case 'msgctxt' :
                        case 'msgid' :
                        case 'msgid_plural' :
                            $temp[$state] .= "\n" . $line;
                            break;
                        case 'msgstr' :
                            $temp[$state][sizeof($temp[$state]) - 1] .= "\n" . $line;
                            break;
                        default :
// parse error
                            fclose($fh);
                            return FALSE;
                    }
                }
                break;
        }
    }
    fclose($fh);

// add final entry
    if ($state == 'msgstr')
        $hash[] = $temp;

// Cleanup data, merge multiline entries, reindex hash for ksort
    $temp = $hash;
    $hash = array ();
    foreach ($temp as $entry) {
        foreach ($entry as & $v) {
            $v = phpmo_clean_helper($v);
            if ($v === FALSE) {
// parse error
                return FALSE;
            }
        }
        $hash[$entry['msgid']] = $entry;
    }

    return $hash;
}

/* Write a GNU gettext style machine object. */
/* @link http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files */
function phpmo_write_mo_file($hash, $out) {
// sort by msgid
    ksort($hash, SORT_STRING);
// our mo file data
    $mo = '';
// header data
    $offsets = array ();
    $ids = '';
    $strings = '';

    foreach ($hash as $entry) {
        $id = $entry['msgid'];
        if (isset ($entry['msgid_plural']))
            $id .= "\x00" . $entry['msgid_plural'];
// context is merged into id, separated by EOT (\x04)
        if (array_key_exists('msgctxt', $entry))
            $id = $entry['msgctxt'] . "\x04" . $id;
// plural msgstrs are NUL-separated
        $str = implode("\x00", $entry['msgstr']);
// keep track of offsets
        $offsets[] = array (
            strlen($ids
            ), strlen($id), strlen($strings), strlen($str));
// plural msgids are not stored (?)
        $ids .= $id . "\x00";
        $strings .= $str . "\x00";
    }

// keys start after the header (7 words) + index tables ($#hash * 4 words)
    $key_start = 7 * 4 + sizeof($hash) * 4 * 4;
// values start right after the keys
    $value_start = $key_start +strlen($ids);
// first all key offsets, then all value offsets
    $key_offsets = array ();
    $value_offsets = array ();
// calculate
    foreach ($offsets as $v) {
        list ($o1, $l1, $o2, $l2) = $v;
        $key_offsets[] = $l1;
        $key_offsets[] = $o1 + $key_start;
        $value_offsets[] = $l2;
        $value_offsets[] = $o2 + $value_start;
    }
    $offsets = array_merge($key_offsets, $value_offsets);

// write header
    $mo .= pack('Iiiiiii', 0x950412de, // magic number
        0, // version
        sizeof($hash), // number of entries in the catalog
        7 * 4, // key index offset
        7 * 4 + sizeof($hash) * 8, // value index offset,
        0, // hashtable size (unused, thus 0)
        $key_start // hashtable offset
    );
// offsets
    foreach ($offsets as $offset)
        $mo .= pack('i', $offset);
// ids
    $mo .= $ids;
// strings
    $mo .= $strings;

    file_put_contents($out, $mo);
}

?>
Если вас одолеет лень, то можно взять тут.
Код - супер) Только куда его вставить? Можно хоть в 2х словах пошаговое руководство?))) Штука просто супер нужная!
 
Код - супер) Только куда его вставить? Можно хоть в 2х словах пошаговое руководство?))) Штука просто супер нужная!
Это код для не для того что бы вставить, а для разработки плагина для перевода.
Ссылка тоже есть , где этот плагин находится;)

Отобразить количество объявлений.
По пути:
--> /oc-content/plugins/list_seller_items --> index.php

Код:
function seller_post() {
  if(osc_get_preference('rewriteEnabled', 'osclass') <> 1) {
    $url = osc_base_url() . 'index.php?page=search&seller_post=' . osc_item_user_id();
  } else {
    $url = osc_base_url() . 'search/seller_post,' . osc_item_user_id() . '/iPage';
  }

  $user = User::newInstance()->findByPrimaryKey(osc_item_user_id());

  if ( osc_item_user_id() <> 0 ) {
    echo '<a id="inzerat_icohref" href="'. $url . '">';
    echo $user['i_items'] . ' ' . ($user['i_items'] == 1 ? __('item', 'list_seller_items') : __('items', 'list_seller_items'));
    echo '</a>';
  }
}
Код:
if(osc_item_user_id() <> 0) {
          $item_user = User::newInstance()->findByPrimaryKey(osc_item_user_id());
          View::newInstance()->_exportVariableToView('user', $item_user);
          $user_item_count = $item_user['i_items'];
          //output
          echo $user_item_count ;
      }
 
Назад
Верх