Информация Доработка тем, плагинов, ядра

_kot

BEng
Команда форума
Модератор
Регистрация
16 Ноя 2018
Сообщения
210
Реакции
264
  • Автор темы
  • Модер.
  • #1
Делимся полезностями для OSCLASS, темы + плагины
Только код с решением + описание, без вопросов и флуда!

Например

Реализация поиска по части слова, а не целиком + поиск объявлений используя юзера по имени
В файл темы 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 ЕЛЕНА
 
Последнее редактирование:
  • Автор темы
  • Модер.
  • #2
Plugin User Rating Plugin 1.1.1 (mb-themes)
в админке:
1. добавим последний IP юзера
2. e-mail кому конкретно была дана оценка
3. линк на е-mail - a вдруг это злостный продавец и обманщик ? ) (сразу в бан)

до
Screenshot 2019-06-22 at 14.32.51.png
после
Screenshot 2019-06-22 at 15.52.37.png

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 ... -->
 
Последнее редактирование:
osclass Не работает мультиязычный поиск!

Я уже выкладывал это где-то на форуме. Но на всякий кину в этой ветке так как это по теме!

В теме veronika Не работает мультиязычный поиск, зависит от самой темы.

Суть.

Сайт мультиязычный (русский и английский)

1.
Если при добавлении объявления заполнить на русском (к примеру "Двери") а английский не заполнять то в фронтенде на сайте при английской локализации выполняя поисковой запрос "Двери" будет со значением "0".

2.
Если при добавлении объявления заполнить на русском и на английском (к примеру на русском "Двери" а на английском "Doors") то в фронтенде на сайте при английской локализации выполняя поисковой запрос "Двери" будет со значением "0".

Что есть не очень хорошо!!!

Делаем чтобы если при добавлении объявления заполнить на русском (к примеру "Двери") а английский не заполнять, или русском и на английском (к примеру на русском "Двери" а на английском "Doors") то в фронтенде на сайте при английской локализации выполняя поисковой запрос "Двери" будет со значением на русском "Двери" а на английском "Doors".

Тоисть независимо от выбранной локализации сайта объявление будет найдено пользователем.

Решение:

По пути oc-content/themes/ВАША-ТЕМА/functions.php

в самый конец после "?>" добавляем ниже выложеный код. В конце Не должно быть пустых строк!
Код:
<?php
function cust_refined_pattern_search($params) {
    if (@$params['sPattern'] != '') {
        $mSearch = Search::newInstance();
        $query_elements = (array) json_decode($mSearch->toJson());
       
        $mSearch->addLocale('%');
        $mSearch->addGroupBy(DB_TABLE_PREFIX.'t_item.pk_i_id');
        if (@$params['sOrder'] != 'i_price') {
            $mSearch->addJoinTable(count($query_elements['tables_join']), sprintf("(SELECT fk_i_item_id, MATCH(s_title, s_description) AGAINST('%s') AS relevance FROM %st_item_description) des", $params['sPattern'], DB_TABLE_PREFIX), 'des.fk_i_item_id = '.DB_TABLE_PREFIX.'t_item.pk_i_id', 'INNER' );
            $mSearch->order("des.relevance DESC, dt_pub_date", "DESC");
        }       
    }
}

osc_add_hook('search_conditions', 'cust_refined_pattern_search');

function cust_alerts_user_dashboard() {
    if (Params::getParam('page') == "user" && Params::getParam('action') == "alerts") {
        $webUser = new CWebUser;

        $aAlerts = Alerts::newInstance()->findByUser( Session::newInstance()->_get('userId'), false );
        $user = User::newInstance()->findByPrimaryKey( Session::newInstance()->_get('userId'));
        foreach($aAlerts as $k => $a) {
            $array_conditions   = (array)json_decode($a['s_search']);

            $search = new Search();
            $search->setJsonAlert($array_conditions);
            if (osc_version() > 361) $search->notFromUser(Session::newInstance()->_get('userId'));
            $search->addLocale('%');
            $search->addGroupBy(DB_TABLE_PREFIX.'t_item.pk_i_id');
            $search->limit(0, 3);

            $aAlerts[$k]['items'] = $search->doSearch();
        }

        $webUser->_exportVariableToView('alerts', $aAlerts);
        View::newInstance()->_reset('alerts');
        $webUser->_exportVariableToView('user', $user);
    }
}

osc_add_hook('before_html', 'cust_alerts_user_dashboard');
?>
 
Последнее редактирование:
  • Автор темы
  • Модер.
  • #4
Проявился еще один плагин, который помогает реализовать турбо страницы у яндекса.:)
Для чего нужны турбо страницы, объяснять не стоит.
Индексация каждый час, с удивительным выводом в поисковике.:cool:
Хотелось бы увидеть что-то подобное у гугла

Для просмотра ссылки Войди или Зарегистрируйся

Проверено яндексом.
Для просмотра ссылки Войди или Зарегистрируйся

Ну и сама ссылка в поиске Для просмотра ссылки Войди или Зарегистрируйся, и как oн отдает в поисковике.
 
Последнее редактирование:
  • Автор темы
  • Модер.
  • #5
Реализация push notification для вашего андроида
используем гугля конечно, доки тут :
Для просмотра ссылки Войди или Зарегистрируйся

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());
    }


}

 
Последнее редактирование:
Отображение аватарок из плагина Profile Picture в переписке плагина сообщений Ultimate Messaging

Чтобы в сообщениях отображались картинки (аватарки) профиля, загруженные плагином Profile Picture, который идет в комплекте с темой Veronika, необходимо в файле /oc-content/plugins/uMessages/user/messages-view.php найти код (у меня это 58 строка)
Код:
<a href="<?php echo osc_user_public_profile_url($message['fk_i_user_id']); ?>" title=""><img src="<?php echo osc_base_url() . 'oc-content/plugins/uMessages/assets/images/user_default.gif'; ?>" alt="<?php echo osc_esc_html($message['s_name']); ?>"></a>
и заменить на следующий код:
Код:
<a class="picture tr1" href="<?php echo osc_user_public_profile_url($message['fk_i_user_id']); ?>"><?php profile_picture_show(null, null, 40, null, $message['fk_i_user_id']); ?></a>
 
  • Автор темы
  • Модер.
  • #7
Автозаполнение категории
Допустим, юзер что-то ищет в определенной категории, или зашел в объявление и решил подать новое объявление, давайте поможем ему автозаполнить категорию в которой он находится:eek::)

1. добавим код в function.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'];
    //check if user can post to parent category
    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 osc post url
            $path = osc_item_post_url();

    }
    return $path;
}

2. меняем функцию для кнопки подачи объявления osc_item_post_url(); на sz_item_post_url_in_category();

если включен live search с использованием ajax, то придется дописать еще JS, в зависимости от темы :wtf:, но принцип ясен:)
 
Последнее редактирование:
  • Автор темы
  • Модер.
  • #8
whatsapp.png Screenshot 2020-08-02 at 22.17.02.png Screenshot 2020-08-02 at 22.19.09.png
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. Наслаждаемся :eek::)
 

Вложения

  • floating-wpp.min.js.zip
    3,9 KB · Просмотры: 23
  • floating-wpp.min.css.zip
    841 байт · Просмотры: 21
  • Автор темы
  • Модер.
  • #9
Если надоело переводить плагины сторонними прогами, то можно это делать сразу на сервере, а желательно с админки.
Идея в том - что бы закомпилить МО файл с переведенного ПО файла.
Вот собственно и код:
Код:
<?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);
}

?>
Если вас одолеет лень, то можно взять Для просмотра ссылки Войди или Зарегистрируйся.
 
Подскажите, можно ли в плагине User Rating 1.1.1 в модальном окне прикрутить крестик для закрытия?
 
Назад
Сверху