Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @package Get statistics
- * @version 1.0
- */
- /*
- Plugin Name: Get statistics VoIP call
- Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
- Author: Vladimir Tatarnikov
- Version: 1.0
- Author URI: http://tatarnikovblog.tk/
- */
- if( ! class_exists( 'WP_List_Table' ) ) {
- require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
- }
- class Payment_List_Table extends WP_List_Table {
- var $example_data;
- var $found_data;
- function get_columns(){
- $columns = array(
- 'cb' => '<input type="checkbox" />',
- 'user' => 'Пользователь',
- 'log_date' => 'Дата платежа',
- 'sum_before' => 'Сумма до',
- 'summa' => 'Сумма',
- 'sum_after' => 'Сумма после',
- 'destination' => 'Назначение платежа'
- );
- return $columns;
- }
- function column_default($item, $column_name ) {
- switch($column_name ) {
- case 'user':
- case 'sum_before':
- case 'summa':
- case 'sum_after':
- case 'destination':
- case 'log_date':
- return $item[ $column_name ];
- default:
- return print_r($item, true ) ; //Мы отображаем целый массив во избежание проблем
- }
- }
- function column_cb($item) {
- return sprintf(
- '<input type="checkbox" name="book[]" value="%s" />', $item['ID']
- );
- }
- function column_account_internal($item) {
- return sprintf(
- '<input type="checkbox" name="account_internal[]" %s />', checked($item['account_internal'], true, false)
- );
- }
- function get_sortable_columns() {
- $sortable_columns = array(
- 'user' => array('user',false)
- );
- return $sortable_columns;
- }
- function prepare_items() {
- $columns = $this->get_columns();
- $hidden = array();
- $sortable = $this->get_sortable_columns();
- $this->_column_headers = array($columns, $hidden, $sortable);
- $per_page = 5;
- $current_page = $this->get_pagenum();
- $total_items = count($this->example_data);
- // необходимо только потому, что у нас пример данных
- $this->found_data = array_slice($this->example_data,(($current_page-1)*$per_page),$per_page);
- $this->set_pagination_args(array(
- 'total_items' => $total_items, //Мы должны вычислить общее количество элементов
- 'per_page' => $per_page //Мы должны определить, сколько элементов отображается на странице
- ) );
- $this->items = $this->found_data;
- }
- function get_bulk_actions() {
- $actions = array(
- 'delete' => 'Удалить'
- );
- return $actions;
- }
- function process_action(){
- $action = $this->current_action();
- if ($action=='update'){
- if (isset($_GET['account'])){
- //update_accounts((int)$_GET['account']);
- }
- }
- }
- }
- class Mountly_Payment_List_Table extends WP_List_Table {
- var $example_data;
- var $found_data;
- function get_columns(){
- $columns = array(
- 'cb' => '<input type="checkbox" />',
- 'user' => 'Пользователь',
- 'summa' => 'Сумма',
- 'day' => 'День платежа',
- 'destination' => 'Назначение платежа'
- );
- return $columns;
- }
- function column_default($item, $column_name ) {
- switch($column_name ) {
- case 'user':
- case 'summa':
- case 'day':
- case 'destination':
- return $item[ $column_name ];
- default:
- return print_r($item, true ) ; //Мы отображаем целый массив во избежание проблем
- }
- }
- function column_cb($item) {
- return sprintf(
- '<input type="checkbox" name="book[]" value="%s" />', $item['ID']
- );
- }
- function column_user($item){
- $actions = array(
- 'edit' => sprintf('<a href="?page=payment_new.php&action=%s&payment=%s">Изменить</a>','edit',$item['id']),
- 'delete' => sprintf('<a href="?page=%s&action=%s&payment=%s">Удалить</a>',$_REQUEST['page'],'delete',$item['id']),
- );
- return sprintf('%1$s %2$s', $item['user'], $this->row_actions($actions));
- }
- function column_account_internal($item) {
- return sprintf(
- '<input type="checkbox" name="account_internal[]" %s />', checked($item['account_internal'], true, false)
- );
- }
- function get_sortable_columns() {
- $sortable_columns = array(
- 'user' => array('user',false)
- );
- return $sortable_columns;
- }
- function prepare_items() {
- $columns = $this->get_columns();
- $hidden = array();
- $sortable = $this->get_sortable_columns();
- $this->_column_headers = array($columns, $hidden, $sortable);
- $per_page = 5;
- $current_page = $this->get_pagenum();
- $total_items = count($this->example_data);
- // необходимо только потому, что у нас пример данных
- $this->found_data = array_slice($this->example_data,($current_page-1)*$per_page,$per_page, true);
- $this->set_pagination_args(array(
- 'total_items' => $total_items, //Мы должны вычислить общее количество элементов
- 'per_page' => $per_page //Мы должны определить, сколько элементов отображается на странице
- ) );
- $this->items = $this->found_data;
- }
- function get_bulk_actions() {
- $actions = array(
- 'delete' => 'Удалить'
- );
- return $actions;
- }
- function process_action(){
- global $wpdb;
- $action = $this->current_action();
- if ($action=='update'){
- if (isset($_GET['account'])){
- update_accounts((int)$_GET['account']);
- }
- } elseif ($action=='delete'){
- if (isset($_GET['payment'])){
- $wpdb->delete( $wpdb->prefix.users_payments, array('id' => (int)$_GET['payment']), array( '%d' ));
- }
- }
- }
- public function get_pagenum() {
- $pagenum = isset( $_REQUEST['paged_mon'] ) ? absint( $_REQUEST['paged_mon'] ) : 0;
- if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
- $pagenum = $this->_pagination_args['total_pages'];
- return max( 1, $pagenum );
- }
- protected function pagination( $which ) {
- if ( empty( $this->_pagination_args ) ) {
- return;
- }
- $total_items = $this->_pagination_args['total_items'];
- $total_pages = $this->_pagination_args['total_pages'];
- $infinite_scroll = false;
- if ( isset( $this->_pagination_args['infinite_scroll'] ) ) {
- $infinite_scroll = $this->_pagination_args['infinite_scroll'];
- }
- if ( 'top' === $which && $total_pages > 1 ) {
- $this->screen->render_screen_reader_content( 'heading_pagination' );
- }
- $output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items ), number_format_i18n( $total_items ) ) . '</span>';
- $current = $this->get_pagenum();
- $removable_query_args = wp_removable_query_args();
- $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
- $current_url = remove_query_arg( $removable_query_args, $current_url );
- $page_links = array();
- $total_pages_before = '<span class="paging-input">';
- $total_pages_after = '</span></span>';
- $disable_first = $disable_last = $disable_prev = $disable_next = false;
- if ( $current == 1 ) {
- $disable_first = true;
- $disable_prev = true;
- }
- if ( $current == 2 ) {
- $disable_first = true;
- }
- if ( $current == $total_pages ) {
- $disable_last = true;
- $disable_next = true;
- }
- if ( $current == $total_pages - 1 ) {
- $disable_last = true;
- }
- if ( $disable_first ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">«</span>';
- } else {
- $page_links[] = sprintf( "<a class='first-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( remove_query_arg( 'paged_mon', $current_url ) ),
- __( 'First page' ),
- '«'
- );
- }
- if ( $disable_prev ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">‹</span>';
- } else {
- $page_links[] = sprintf( "<a class='prev-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( add_query_arg( 'paged_mon', max( 1, $current-1 ), $current_url ) ),
- __( 'Previous page' ),
- '‹'
- );
- }
- if ( 'bottom' === $which ) {
- $html_current_page = $current;
- $total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
- } else {
- $html_current_page = sprintf( "%s<input class='current-page' id='current-page-selector' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
- '<label for="current-page-selector" class="screen-reader-text">' . __( 'Current Page' ) . '</label>',
- $current,
- strlen( $total_pages )
- );
- }
- $html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
- $page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging' ), $html_current_page, $html_total_pages ) . $total_pages_after;
- if ( $disable_next ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">›</span>';
- } else {
- $page_links[] = sprintf( "<a class='next-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( add_query_arg( 'paged_mon', min( $total_pages, $current+1 ), $current_url ) ),
- __( 'Next page' ),
- '›'
- );
- }
- if ( $disable_last ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">»</span>';
- } else {
- $page_links[] = sprintf( "<a class='last-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( add_query_arg( 'paged_mon', $total_pages, $current_url ) ),
- __( 'Last page' ),
- '»'
- );
- }
- $pagination_links_class = 'pagination-links';
- if ( ! empty( $infinite_scroll ) ) {
- $pagination_links_class .= ' hide-if-js';
- }
- $output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
- if ( $total_pages ) {
- $page_class = $total_pages < 2 ? ' one-page' : '';
- } else {
- $page_class = ' no-pages';
- }
- $this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
- echo $this->_pagination;
- }
- }
- class Dayly_Payment_List_Table extends WP_List_Table {
- var $example_data;
- var $found_data;
- function get_columns(){
- $columns = array(
- 'cb' => '<input type="checkbox" />',
- 'user' => 'Пользователь',
- 'summa' => 'Сумма',
- 'destination' => 'Назначение платежа'
- );
- return $columns;
- }
- function column_default($item, $column_name ) {
- switch($column_name ) {
- case 'user':
- case 'summa':
- case 'destination':
- return $item[ $column_name ];
- default:
- return print_r($item, true ) ; //Мы отображаем целый массив во избежание проблем
- }
- }
- function column_cb($item) {
- return sprintf(
- '<input type="checkbox" name="book[]" value="%s" />', $item['ID']
- );
- }
- function column_user($item){
- $actions = array(
- 'edit' => sprintf('<a href="?page=payment_new.php&action=%s&payment=%s">Изменить</a>','edit',$item['id']),
- 'delete' => sprintf('<a href="?page=%s&action=%s&payment=%s">Удалить</a>',$_REQUEST['page'],'delete',$item['id']),
- );
- return sprintf('%1$s %2$s', $item['user'], $this->row_actions($actions));
- }
- function column_account_internal($item) {
- return sprintf(
- '<input type="checkbox" name="account_internal[]" %s />', checked($item['account_internal'], true, false)
- );
- }
- function get_sortable_columns() {
- $sortable_columns = array(
- 'user' => array('user',false)
- );
- return $sortable_columns;
- }
- function prepare_items() {
- $columns = $this->get_columns();
- $hidden = array();
- $sortable = $this->get_sortable_columns();
- $this->_column_headers = array($columns, $hidden, $sortable);
- $per_page = 5;
- $current_page = $this->get_pagenum();
- $total_items = count($this->example_data);
- // необходимо только потому, что у нас пример данных
- $this->found_data = array_slice($this->example_data,($current_page-1)*$per_page,$per_page, true);
- $this->set_pagination_args(array(
- 'total_items' => $total_items, //Мы должны вычислить общее количество элементов
- 'per_page' => $per_page //Мы должны определить, сколько элементов отображается на странице
- ) );
- $this->items = $this->found_data;
- }
- function get_bulk_actions() {
- $actions = array(
- 'delete' => 'Удалить'
- );
- return $actions;
- }
- function process_action(){
- global $wpdb;
- $action = $this->current_action();
- if ($action=='update'){
- if (isset($_GET['account'])){
- update_accounts((int)$_GET['account']);
- }
- } elseif ($action=='delete'){
- if (isset($_GET['payment'])){
- $wpdb->delete( $wpdb->prefix.users_payments, array('id' => (int)$_GET['payment']), array( '%d' ));
- }
- }
- }
- public function get_pagenum() {
- $pagenum = isset( $_REQUEST['paged_day'] ) ? absint( $_REQUEST['paged_day'] ) : 0;
- if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
- $pagenum = $this->_pagination_args['total_pages'];
- return max( 1, $pagenum );
- }
- protected function pagination( $which ) {
- if ( empty( $this->_pagination_args ) ) {
- return;
- }
- $total_items = $this->_pagination_args['total_items'];
- $total_pages = $this->_pagination_args['total_pages'];
- $infinite_scroll = false;
- if ( isset( $this->_pagination_args['infinite_scroll'] ) ) {
- $infinite_scroll = $this->_pagination_args['infinite_scroll'];
- }
- if ( 'top' === $which && $total_pages > 1 ) {
- $this->screen->render_screen_reader_content( 'heading_pagination' );
- }
- $output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items ), number_format_i18n( $total_items ) ) . '</span>';
- $current = $this->get_pagenum();
- $removable_query_args = wp_removable_query_args();
- $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
- $current_url = remove_query_arg( $removable_query_args, $current_url );
- $page_links = array();
- $total_pages_before = '<span class="paging-input">';
- $total_pages_after = '</span></span>';
- $disable_first = $disable_last = $disable_prev = $disable_next = false;
- if ( $current == 1 ) {
- $disable_first = true;
- $disable_prev = true;
- }
- if ( $current == 2 ) {
- $disable_first = true;
- }
- if ( $current == $total_pages ) {
- $disable_last = true;
- $disable_next = true;
- }
- if ( $current == $total_pages - 1 ) {
- $disable_last = true;
- }
- if ( $disable_first ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">«</span>';
- } else {
- $page_links[] = sprintf( "<a class='first-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( remove_query_arg( 'paged_day', $current_url ) ),
- __( 'First page' ),
- '«'
- );
- }
- if ( $disable_prev ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">‹</span>';
- } else {
- $page_links[] = sprintf( "<a class='prev-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( add_query_arg( 'paged_day', max( 1, $current-1 ), $current_url ) ),
- __( 'Previous page' ),
- '‹'
- );
- }
- if ( 'bottom' === $which ) {
- $html_current_page = $current;
- $total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
- } else {
- $html_current_page = sprintf( "%s<input class='current-page' id='current-page-selector' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
- '<label for="current-page-selector" class="screen-reader-text">' . __( 'Current Page' ) . '</label>',
- $current,
- strlen( $total_pages )
- );
- }
- $html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
- $page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging' ), $html_current_page, $html_total_pages ) . $total_pages_after;
- if ( $disable_next ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">›</span>';
- } else {
- $page_links[] = sprintf( "<a class='next-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( add_query_arg( 'paged_day', min( $total_pages, $current+1 ), $current_url ) ),
- __( 'Next page' ),
- '›'
- );
- }
- if ( $disable_last ) {
- $page_links[] = '<span class="tablenav-pages-navspan" aria-hidden="true">»</span>';
- } else {
- $page_links[] = sprintf( "<a class='last-page' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
- esc_url( add_query_arg( 'paged_day', $total_pages, $current_url ) ),
- __( 'Last page' ),
- '»'
- );
- }
- $pagination_links_class = 'pagination-links';
- if ( ! empty( $infinite_scroll ) ) {
- $pagination_links_class .= ' hide-if-js';
- }
- $output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
- if ( $total_pages ) {
- $page_class = $total_pages < 2 ? ' one-page' : '';
- } else {
- $page_class = ' no-pages';
- }
- $this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
- echo $this->_pagination;
- }
- }
- class Account_List_Table extends WP_List_Table {
- var $example_data;
- var $found_data;
- function get_columns(){
- $columns = array(
- 'cb' => '<input type="checkbox" />',
- 'user' => 'Пользователь',
- 'account_token' => 'Токен',
- 'custom_update' => 'Обновлять вручную'
- );
- return $columns;
- }
- function column_default($item, $column_name ) {
- switch($column_name ) {
- case 'user':
- case 'account_token':
- case 'custom_update':
- return $item[ $column_name ];
- default:
- return print_r($item, true ) ; //Мы отображаем целый массив во избежание проблем
- }
- }
- function column_user($item) {
- $actions = array(
- 'edit' => sprintf('<a href="?page=account_new.php&action=%s&account=%s">Изменить</a>','edit',$item['id']),
- 'delete' => sprintf('<a href="?page=%s&action=%s&account=%s">Удалить</a>',$_REQUEST['page'],'delete',$item['id']),
- 'update' => sprintf('<a href="?page=%s&action=%s&account=%s">Обновить</a>',$_REQUEST['page'],'update',$item['id']),
- );
- return sprintf('%1$s %2$s', $item['user'], $this->row_actions($actions));
- }
- function column_cb($item) {
- return sprintf(
- '<input type="checkbox" name="book[]" value="%s" />', $item['ID']
- );
- }
- function column_custom_update($item) {
- return sprintf(
- '<input type="checkbox" name="account[]" "%s" disabled/>', checked($item['custom_update'], true, false)
- );
- }
- function get_sortable_columns() {
- $sortable_columns = array(
- 'user' => array('user',false)
- );
- return $sortable_columns;
- }
- function prepare_items() {
- $columns = $this->get_columns();
- $hidden = array();
- $sortable = $this->get_sortable_columns();
- $this->_column_headers = array($columns, $hidden, $sortable);
- $per_page = 5;
- $current_page = $this->get_pagenum();
- $total_items = count($this->example_data);
- // необходимо только потому, что у нас пример данных
- $this->found_data = array_slice($this->example_data,(($current_page-1)*$per_page),$per_page);
- $this->set_pagination_args(array(
- 'total_items' => $total_items, //Мы должны вычислить общее количество элементов
- 'per_page' => $per_page //Мы должны определить, сколько элементов отображается на странице
- ) );
- $this->items = $this->found_data;
- }
- function get_bulk_actions() {
- $actions = array(
- 'delete' => 'Удалить'
- );
- return $actions;
- }
- function process_action(){
- global $wpdb;
- $action = $this->current_action();
- if ($action=='update'){
- if (isset($_GET['account'])){
- update_accounts((int)$_GET['account']);
- }
- } elseif ($action=='delete'){
- if (isset($_GET['account'])){
- $wpdb->delete( $wpdb->prefix.users_accounts, array('id' => (int)$_GET['account']), array( '%d' ));
- $wpdb->delete( $wpdb->prefix.users_accounts_sip, array('users_accounts_id' => (int)$_GET['account']), array( '%d' ));
- //header("Location: ?page=accounts.php");
- }
- }
- }
- }
- function is_timezone($str){
- return in_array($str, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC));
- }
- function set_timezone($date, $timezone){
- if (is_timezone($timezone)){
- $date->setTimezone(new DateTimeZone($timezone));
- $interval = new DateInterval('PT'.$date->getOffset().'S');
- return $interval;
- } else {
- $user_timezone = str_replace('UTC', '', $timezone);
- $h_offset = (int)$timezone;
- $m_offset = (int)(((float)$timezone - $h_offset)*60);
- $interval = new DateInterval('PT'.$h_offset.'H'.$m_offset.'M');
- $date->add($interval);
- return $interval;
- }
- }
- function tatarnikov_add_admin_pages(){
- add_menu_page('Аккаунты и токены пользователей', 'Аккаунты', 8, 'accounts.php', 'accounts_menu_page');
- add_submenu_page('accounts.php', 'Новый аккаунт пользователя', 'Добавить аккаунт', 8, 'account_new.php', 'account_page');
- add_menu_page('история платежей', 'Платежи', 8, 'payments.php', 'payments_menu_page');
- add_submenu_page('payments.php', 'Ежедневные платежи', 'Ежедневные платежи', 8, 'dayly_payment_new.php', 'dayly_payment_page');
- add_submenu_page('payments.php', 'Ежемесячные платежи', 'Ежемесячные платежи', 8, 'monthly_payment_new.php', 'monthly_payment_page');
- add_submenu_page('payments.php', 'Новый платеж', 'Новый платеж', 8, 'payment_new.php', 'payment_page');
- }
- function get_money($duration, $user_id, $calltype){
- $tarif_type = get_the_author_meta("tarif_type", $user_id);
- $tarif_value = get_the_author_meta("tarif_value", $user_id);
- $tarif_delay_sec = get_the_author_meta("tarif_delay_sec", $user_id);
- $minutes = (int)($duration / 60);
- $seconds = $duration - $minutes*60;
- $money = 0;
- if ($duration > $tarif_delay_sec && $calltype == "xsi:CallOriginatedEvent"){
- if ($tarif_type == 1){
- $minutes_full = ($seconds==0?$minutes:$minutes+1);
- $money = round($minutes_full * $tarif_value, 2);
- } elseif ($tarif_type == 0){
- $money = round($duration * $tarif_value/60, 2);
- };
- }
- return $money;
- }
- function is_checked($chkname,$value){
- if(!empty($_POST[$chkname])){
- foreach($_POST[$chkname] as $chkval){
- if($chkval == $value){
- return true;
- }
- }
- }
- return false;
- }
- function accounts_menu_page(){
- global $wpdb;
- $table_accounts = $wpdb->prefix.users_accounts;
- $myListTable = new Account_List_Table();
- $myListTable->example_data = $wpdb->get_results(
- "
- SELECT acc.*, us.user_login as user FROM $table_accounts as acc
- left join getstats_wp_users us on us.id = acc.user_id
- ",
- "ARRAY_A"
- );
- echo '<div class="wrap"><h1 class="wp-heading-inline">SIP аккаунты пользователей</h1>';
- echo "<a class='page-title-action' href='?page=account_new.php'>Добавить</a>";
- $myListTable->prepare_items();
- echo $myListTable->search_box('Найти', 'search_account');
- $myListTable->display();
- echo '</div>';
- }
- function account_page(){
- global $wpdb;
- $users = get_users();
- $user_id = -1;
- $token = '';
- $edit = false;
- if (isset($_GET['account'])){
- $account_id = $_GET['account'];
- $table_accounts = $wpdb->prefix.users_accounts;
- $account_row = $wpdb->get_row(
- "
- SELECT * FROM $table_accounts where id = $account_id
- "
- );
- $user_id = $account_row->user_id;
- $token = $account_row->account_token;
- $custom_update = $account_row->custom_update;
- }
- if (isset($_GET['action'])){
- $edit = $_GET['action']=='edit';
- }
- if (isset($_POST['action'])){
- $table_account = $wpdb->prefix.users_accounts;
- $update_data = array(
- 'user_id'=>$_POST['user'],
- 'account_token'=>$_POST['token'],
- 'custom_update'=>$_POST['custom_update']==="on",
- );
- $sips = array();
- $table_sip = $wpdb->prefix.users_accounts_sip;
- if ($update_data['account_token'] != ""){
- if ($curl = curl_init()){
- $headers = array(
- "X-MPBX-API-AUTH-TOKEN: ".$update_data['account_token']
- );
- curl_setopt($curl, CURLOPT_URL,"https://cloudpbx.beeline.ru/apis/portal/abonents");
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $out = curl_exec($curl);
- $abonents = json_decode($out);
- foreach ($abonents as $abonent){
- $sips[$abonent->userId] = is_checked("sips", $abonent->userId);
- }
- }
- }
- print_r($_POST, true);
- if ($_POST['action']=='edit'){
- $wpdb->update($table_account, $update_data, array('id'=>(int)$_POST['account']));
- $user_id = $update_data['user_id'];
- $token = $update_data['account_token'];
- $custom_update = $update_data['custom_update'];
- foreach($sips as $key=>$value){
- $current_id = $wpdb->get_var($wpdb->prepare("select id from $table_sip where users_accounts_id = %d and sip = '%s' limit 1", (int)$_POST['account'], $key));
- if (!is_null($current_id)){
- $updated = $wpdb->update($table_sip, array('select_sip'=>$value), array('id'=>$current_id), array('%d'), array('%d'));
- } else {
- $wpdb->insert($table_sip, array('users_accounts_id'=>(int)$_POST['account'], 'sip'=>$key, 'select_sip'=>$value), array('%d','%s','%d'));
- }
- }
- } elseif ($_POST['action']=='add'){
- $res = $wpdb->insert($table_account, $update_data);
- $last_id = $wpdb->insert_id;
- if ($res){
- update_accounts($last_id);
- } else {
- }
- foreach($sips as $key=>$value){
- $wpdb->insert($table_sip, array('users_accounts_id'=>$last_id, 'sip'=>$key, 'select_sip'=>$value), array('%d','%s','%d'));
- }
- }
- }
- if ($token != ""){
- if ($curl = curl_init()){
- $headers = array(
- "X-MPBX-API-AUTH-TOKEN: ".$token
- );
- curl_setopt($curl, CURLOPT_URL,"https://cloudpbx.beeline.ru/apis/portal/abonents");
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $out = curl_exec($curl);
- $abonents = json_decode($out);
- }
- }
- echo "<script type='text/javascript'>
- function get_abonents(token){
- var request = new XMLHttpRequest();
- request.open('GET','https://cloudpbx.beeline.ru/apis/portal/abonents',true);
- request.setRequestHeader('X-MPBX-API-AUTH-TOKEN', token);
- request.addEventListener('readystatechange', function(){
- alert(request.response);
- });
- request.send();
- }
- </script>";
- echo "<h1 class='wp-heading-inline'>Добавить аккаунт</h1>";
- echo "
- <form name='getstats_form_settings' method='post' action='".$_SERVER['PHP_SELF']."?page=account_new.php".($edit?'&action=edit&account='.$account_id.'&updated=true':'')."'>".($edit?'<input type="hidden" name="action" value="edit"><input type="hidden" name="account" value="'.$account_id.'"><input type="hidden" name="updated" value="1">':'<input type="hidden" name="action" value="add">')."
- <table class='form-table'>
- <tr>
- <th scope='row'>Пользователь</th>
- <td>
- <select name='user' required='required'>
- <option value=-1></option>";
- foreach ($users as $user){
- echo sprintf("<option value=%s ".selected($user->ID, $user_id, false).">%s</option>", $user->ID, $user->user_login);
- };
- echo
- "</select>
- </td>
- </tr>
- <tr>
- <th scope='row'>Токен</th>
- <td>
- <!--<input name='token' required='required' value='".$token."' onchange='get_abonents(this.value)'>-->
- <input name='token' required='required' value='".$token."'>
- </td>
- </tr>
- <tr>
- <th scope='row'>Обновлять вручную</th>
- <td>
- <input type='checkbox' name='custom_update' '".checked($custom_update, true, false)."'>
- </td>
- </tr>
- </table>
- <!--<p class='submit'>
- <a class='button' href=''>Обновить список SIP</a>
- </p>-->
- <table id='sips'>
- <th>SIP абонента</th>
- <th>Обновлять</th>";
- foreach ($abonents as $abonent){
- $table_sip = $wpdb->prefix.users_accounts_sip;
- $selected = $wpdb->get_var($wpdb->prepare("SELECT select_sip FROM $table_sip where sip='%s' and users_accounts_id = %d limit 1", $abonent->userId, (int)$_GET['account']));
- echo "<tr><td>$abonent->userId</td><td><input type='checkbox' name='sips[]' value='$abonent->userId' ".checked($selected, true, false)."></td></tr>";
- }
- echo "</table>
- <p class='submit'>
- <input type='submit' value='Сохранить изменения' name='save_new_account' class='button button-primary' id='submit'>
- </p>
- </form>
- ";
- }
- function payments_menu_page(){
- global $wpdb;
- $users = get_users();
- $table_payments = $wpdb->prefix.users_payments;
- $myListTable = new Payment_List_Table();
- $query =
- "
- SELECT acc.*, us.user_login as user FROM $table_payments as acc
- left join getstats_wp_users us on us.id = acc.user_id
- where (acc.periodicity = '' or acc.periodicity is null)
- ";
- if (isset($_GET['user_id']) && $_GET['user_id'] != ''){
- $query = $query." and acc.user_id = ".$_GET['user_id'];
- }
- $myListTable->process_action();
- $myListTable->example_data = $wpdb->get_results(
- $query, "ARRAY_A"
- );
- echo '<div class="wrap"><h1 class="wp-heading-inline">История платежей</h1>';
- echo "<a class='page-title-action' href='?page=payment_new.php'>Новый платеж</a>";
- $myListTable->prepare_items();
- echo "
- <form method='get'>
- <input type='hidden' name='page' value='payments.php'>
- <label for='user_id'>Пользователь</label>
- <select name='user_id'>
- <option value=''></option>";
- foreach($users as $user){
- echo sprintf("<option value=%s ".selected($user->ID, $_GET['user_id'], false).">%s</option>", $user->ID, $user->user_login);
- }
- echo "
- </select>
- <button>Выбрать</button>
- </form>
- ";
- $myListTable->display();
- echo '</div>';
- }
- function dayly_payment_page(){
- global $wpdb;
- $users = get_users();
- $table_payments = $wpdb->prefix.users_payments;
- $myListTable = new Dayly_Payment_List_Table();
- $query =
- "
- SELECT acc.*, us.user_login as user FROM $table_payments as acc
- left join getstats_wp_users us on us.id = acc.user_id
- where acc.periodicity = '1'
- ";
- if (isset($_GET['user_id']) && $_GET['user_id'] != ''){
- $query = $query." and acc.user_id = ".$_GET['user_id'];
- }
- $myListTable->process_action();
- $myListTable->example_data = $wpdb->get_results(
- $query, "ARRAY_A"
- );
- echo '<div class="wrap"><h1 class="wp-heading-inline">Ежедневные платежи</h1>';
- echo "<a class='page-title-action' href='?page=payment_new.php'>Новый платеж</a>";
- $myListTable->prepare_items();
- echo "
- <form method='get'>
- <input type='hidden' name='page' value='dayly_payment_new.php'>
- <label for='user_id'>Пользователь</label>
- <select name='user_id'>
- <option value=''></option>";
- foreach($users as $user){
- echo sprintf("<option value=%s ".selected($user->ID, $_GET['user_id'], false).">%s</option>", $user->ID, $user->user_login);
- }
- echo "
- </select>
- <button>Выбрать</button>
- </form>
- ";
- $myListTable->display();
- echo '</div>';
- }
- function monthly_payment_page(){
- global $wpdb;
- $users = get_users();
- $table_payments = $wpdb->prefix.users_payments;
- $myListTable = new Mountly_Payment_List_Table();
- $query =
- "
- SELECT acc.*, us.user_login as user FROM $table_payments as acc
- left join getstats_wp_users us on us.id = acc.user_id
- where acc.periodicity = '2'
- ";
- if (isset($_GET['user_id']) && $_GET['user_id'] != ''){
- $query = $query." and acc.user_id = ".$_GET['user_id'];
- }
- $myListTable->process_action();
- $myListTable->example_data = $wpdb->get_results(
- $query, "ARRAY_A"
- );
- echo '<div class="wrap"><h1 class="wp-heading-inline">Ежемесячные платежи</h1>';
- echo "<a class='page-title-action' href='?page=payment_new.php'>Новый платеж</a>";
- $myListTable->prepare_items();
- echo "
- <form method='get'>
- <input type='hidden' name='page' value='monthly_payment_new.php'>
- <label for='user_id'>Пользователь</label>
- <select name='user_id'>
- <option value=''></option>";
- foreach($users as $user){
- echo sprintf("<option value=%s ".selected($user->ID, $_GET['user_id'], false).">%s</option>", $user->ID, $user->user_login);
- }
- echo "
- </select>
- <button>Выбрать</button>
- </form>
- ";
- $myListTable->display();
- echo '</div>';
- }
- function payment_page(){
- if (current_user_can('administrator', $args)){
- global $wpdb;
- $users = get_users();
- $user_id = -1;
- $token = '';
- $edit = false;
- if (isset($_GET['payment'])){
- $payment_id = $_GET['payment'];
- $table_accounts = $wpdb->prefix.users_payments;
- $account_row = $wpdb->get_row(
- "
- SELECT * FROM $table_accounts where id = $payment_id
- "
- );
- $user_id = $account_row->user_id;
- //$sum_before = $account_row->sum_before;
- $summa = $account_row->summa;
- $destination = $account_row->destination;
- //$sum_after = $account_row->sum_after;
- $periodicity = $account_row->periodicity;
- $day = $account_row->day;
- }
- if (isset($_GET['action'])){
- $edit = $_GET['action']=='edit';
- }
- if (isset($_POST['action'])){
- $table_payments = $wpdb->prefix.users_payments;
- $balance = get_the_author_meta("balance", $_POST['user']);
- $balance = round((float)$balance, 2);
- $update_data = array(
- 'user_id'=>$_POST['user'],
- //'sum_before'=>$balance,
- 'summa'=>round((float)$_POST['summa'], 2),
- //'sum_after'=>$balance + (float)$_POST['summa'],
- 'destination'=>$_POST['destination'],
- 'periodicity'=>$_POST['periodicity'],
- 'day'=>$_POST['day'],
- );
- if ($_POST['action']=='edit'){
- $wpdb->update($table_payments, $update_data, array('id'=>(int)$_POST['account']));
- $user_id = $update_data['user_id'];
- //$sum_before = $update_data['sum_before'];
- $summa = $update_data['summa'];
- $destination = $update_data['destination'];
- //$sum_after = $update_data['sum_after'];
- $periodicity = $update_data['periodicity'];
- $day = $account_row->day;
- } elseif ($_POST['action']=='add'){
- if ($update_data['periodicity'] == ""){
- $update_data['sum_before'] = $balance;
- $update_data['sum_after'] = $balance + round((float)$_POST['summa'], 2);
- }
- $res = $wpdb->insert($table_payments, $update_data);
- if ($res){
- if ($update_data['periodicity'] == ""){
- update_user_meta($update_data['user_id'], 'balance', $update_data['summa'] + $balance);
- if ($update_data['summa'] + $balance >= 10){
- update_user_meta($update_data['user_id'], 'notify_lt_10', true);
- };
- if ($update_data['summa'] + $balance >= 500){
- update_user_meta($update_data['user_id'], 'notify_lt_500', true);
- };
- if ($update_data['summa'] + $balance >= 1500){
- update_user_meta($update_data['user_id'], 'notify_lt_1500', true);
- };
- }
- } else {
- }
- }
- }
- echo "<h1 class='wp-heading-inline'>Новый платеж</h1>";
- echo "
- <form name='getstats_form_settings' method='post' action='".$_SERVER['PHP_SELF']."?page=payment_new.php".($edit?'&action=edit&payment='.$payment_id.'&updated=true':'')."'>".($edit?'<input type="hidden" name="action" value="edit"><input type="hidden" name="payment" value="'.$payment_id.'"><input type="hidden" name="updated" value="1">':'<input type="hidden" name="action" value="add">')."
- <table class='form-table'>
- <tr>
- <th scope='row'>Пользователь</th>
- <td>
- <select name='user' required='required'>
- <option value=-1></option>";
- foreach ($users as $user){
- echo sprintf("<option value=%s ".selected($user->ID, $user_id, false).">%s</option>", $user->ID, $user->user_login);
- };
- echo
- "</select>
- </td>
- </tr>
- <tr>
- <th scope='row'>Сумма</th>
- <td>
- <input type='number' step='0.01' name='summa' required='required' value='".$summa."'>
- </td>
- </tr>
- <tr>
- <th scope='row'>Назначение платежа</th>
- <td>
- <input name='destination' value='".$destination."'>
- </td>
- </tr>
- <tr>
- <th scope='row'>Периодичность</th>
- <td>
- <select name='periodicity'>
- <option value='' ".selected($periodicity, "", false).">Нет</option>
- <option value='1' ".selected($periodicity, "1", false).">Ежедневно</option>
- <option value='2' ".selected($periodicity, "2", false).">Ежемесячно</option>
- </select>
- </td>
- </tr>
- <tr>
- <th scope='row'>День ежемесячного списания</th>
- <td>
- <select name='day'>";
- for ($i = 1; $i <= 28; $i++) {
- echo sprintf("<option value=%s ".selected($i, $day, false).">%s</option>", $i, $i);
- }
- echo "</select>
- </td>
- </tr>
- </table>
- <p class='submit'>
- <input type='submit' value='Сохранить изменения' name='save_new_payment' class='button button-primary' id='submit'>
- </p>
- </form>
- ";
- } else {
- echo "У Вас недостаточно прав для просмотра данной страницы";
- };
- }
- function update_accounts($account_id, $exclude_sip=array()){
- global $wpdb;
- $table_accounts = $wpdb->prefix.users_accounts;
- $account_row = $wpdb->get_row(
- "
- SELECT * FROM $table_accounts where id = $account_id
- "
- );
- if ($curl = curl_init()){
- $headers = array(
- "X-MPBX-API-AUTH-TOKEN: ".$account_row->account_token
- );
- curl_setopt($curl, CURLOPT_URL,"https://cloudpbx.beeline.ru/apis/portal/abonents");
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $out = curl_exec($curl);
- $abonents = json_decode($out);
- foreach($abonents as $abonent){
- if (!in_array($abonent->extension, $exclude_sip)){
- $put_headers = array(
- "X-MPBX-API-AUTH-TOKEN: ".$account_row->account_token,
- "Content-Type: application/json"
- );
- $put_data = array(
- 'pattern' => $abonent->extension,
- 'expires' => 720,
- 'subscriptionType' => "ADVANCED_CALL",
- 'url' => plugins_url("getstats/callback.php")
- );
- if ($put_curl = curl_init()){
- curl_setopt($put_curl, CURLOPT_URL,"https://cloudpbx.beeline.ru/apis/portal/subscription");
- curl_setopt($put_curl, CURLOPT_HTTPHEADER, $put_headers);
- curl_setopt($put_curl, CURLOPT_CUSTOMREQUEST, "PUT");
- curl_setopt($put_curl, CURLOPT_POSTFIELDS, json_encode($put_data));
- curl_setopt($put_curl, CURLOPT_RETURNTRANSFER, true);
- $out = curl_exec($put_curl);
- };
- }
- }
- }
- }
- function get_statistics($args){
- ob_start();
- if ( is_user_logged_in() ) {
- global $wpdb;
- $table_accounts = $wpdb->prefix.users_accounts;
- $table_calls = $wpdb->prefix.users_calls;
- $current_user = wp_get_current_user();
- $user_timezone = get_the_author_meta("user_timezone", $current_user->ID);
- $account_row = $wpdb->get_row(
- "
- SELECT * FROM $table_accounts where user_id = $current_user->ID
- "
- );
- $datefrom = date('Y-m-01 00:00:00');
- $dateto = date('Y-m-t 23:59:59');
- if (isset($_GET['datefrom'])){
- if ($_GET['datefrom'] !== ""){
- $datefrom = $_GET['datefrom']." 00:00:00";
- }
- };
- if (isset($_GET['dateto'])){
- if ($_GET['dateto'] !== ""){
- $dateto = $_GET['dateto']." 23:59:59";
- }
- };
- //print_r($user_timezone);
- //echo "<br/>";
- $datefrom_select = new DateTime($datefrom);
- //set_timezone($datefrom_select, $user_timezone);
- $datefrom_date = new DateTime($datefrom);
- //$intervalfrom = $datefrom_date->getTimestamp() - $datefrom_select->getTimestamp();
- $intervalfrom = set_timezone($datefrom_select, $user_timezone);
- //print_r($intervalfrom);
- //echo "<br/>";
- //$datefrom_date = $datefrom_date->modify(sprintf(" %s sec", $intervalfrom));
- $datefrom_date = $datefrom_date->sub($intervalfrom);
- print_r($datefrom_date, true);
- //echo "<br/>";
- //print_r($datefrom_select);
- //echo "<br/>";
- $dateto_select = new DateTime($dateto);
- //set_timezone($dateto_select, $user_timezone);
- $dateto_date = new DateTime($dateto);
- //$intervalto = $dateto_date->getTimestamp() - $dateto_select->getTimestamp();
- $intervalto = set_timezone($dateto_select, $user_timezone);
- //$dateto_date = $dateto_date->modify(sprintf(" %s sec", $intervalto));
- $dateto_date = $dateto_date->sub($intervalto);
- print_r($dateto_date, true);
- //echo "<br/>";
- //print_r($dateto_select);
- //echo "<br/>";
- if ($curl = curl_init()){
- $headers = array(
- "X-MPBX-API-AUTH-TOKEN: ".$account_row->account_token
- );
- curl_setopt($curl, CURLOPT_URL,"https://cloudpbx.beeline.ru/apis/portal/abonents");
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $out = curl_exec($curl);
- $abonents = json_decode($out);
- echo "
- <form method='get' action='/'>
- <input type='date' name='datefrom' style='width:32%' value=$datefrom>
- -
- <input type='date' name='dateto' style='width:32%' value=$dateto>
- <button type='submit' style='width:33%'>Выбрать</button>
- </form><br/>";
- echo "<table>";
- echo "<thead><tr><td>Абонент</td><td>Дата</td><td>На номер</td><td>Тип вызова</td><td>Длительность</td><td>Сумма</td></tr></thead>";
- $arraySIP = array();
- $arraySIPname = array();
- foreach($abonents as $abonent){
- $userId = $abonent->userId;
- array_push($arraySIP, $userId);
- $arraySIPname[$userId]=($abonent->lastName?$abonent->lastName:$abonent->firstName);
- }
- $arraySIPstr = implode("', '", $arraySIP);
- if ($account_row->custom_update){
- $table_sip = $wpdb->prefix.users_accounts_sip;
- $arraySIPstr = implode("', '", $wpdb->get_col($wpdb->prepare("select sip from $table_sip where users_accounts_id=%d and select_sip=1", $account_row->id)));
- }
- global $wp_query;
- $pages = '';
- $posts_per_page = get_option('posts_per_page');
- $max = ceil($wpdb->get_var(
- "select COUNT(*)
- from $table_calls uc
- left join $table_calls ic on ic.extTrackingId = uc.extTrackingId and
- ic.address is not null and
- ic.startTime = uc.startTime and
- ic.state = 'Alerting' and
- ic.eventData = 'xsi:CallOriginatedEvent'
- where uc.targetId in ('$arraySIPstr') and
- uc.releaseTime is not null and
- uc.answerTime is not null and
- ic.log_datetime is not null and
- ic.log_datetime between '".$datefrom_date->date."' and '".$dateto_date->date."'
- ORDER by 1 desc")/$posts_per_page);
- if (!$current = get_query_var('page')) $current = 1;
- $a['base'] = str_replace(999999999, '%#%', get_pagenum_link(999999999));
- $a['total'] = $max;
- $a['current'] = $current;
- $results = $wpdb->get_results(
- "select ic.log_datetime,
- ic.address as address,
- uc.answerTime,
- uc.releaseTime,
- uc.targetId,
- (select ct.eventData from $table_calls as ct where ct.extTrackingId = uc.extTrackingId and ct.eventData in ('xsi:CallOriginatedEvent', 'xsi:CallReceivedEvent') and ct.startTime = uc.startTime limit 1) as calltype
- from $table_calls uc
- left join $table_calls ic on ic.extTrackingId = uc.extTrackingId and
- ic.address is not null and
- ic.startTime = uc.startTime and
- ic.state = 'Alerting' and
- ic.eventData = 'xsi:CallOriginatedEvent'
- where uc.targetId in ('$arraySIPstr') and
- uc.releaseTime is not null and
- uc.answerTime is not null and
- ic.log_datetime is not null and
- ic.log_datetime between '".$datefrom_date->date."' and '".$dateto_date->date."'
- ORDER by 1 desc limit ".$posts_per_page*($current-1).", ".$posts_per_page
- ,
- "ARRAY_A"
- );
- foreach($results as $res){
- $duration = (int)(((int)$res['releaseTime'] - (int)$res['answerTime'])/1000);
- $minutes = (int)($duration / 60);
- $seconds = $duration - $minutes*60;
- if (strlen($res['address']) == 3) {
- $res['calltype'] = 'inner';
- }
- $money = get_money($duration, $current_user->ID, $res['calltype']);
- $date = new DateTime($res['log_datetime']);
- set_timezone($date, $user_timezone);
- $calltype = "-";
- if ($res['calltype'] == "xsi:CallOriginatedEvent"){
- $calltype = "Исх.";
- } elseif ($res['calltype'] == "xsi:CallReceivedEvent"){
- $calltype = "Вх.";
- } elseif ($res['calltype'] == "inner"){
- $calltype = "Внутр.";
- }
- echo "<tr>";
- echo "<td>".$arraySIPname[$res['targetId']]."</td>", "<td>".$date->format('d.m.Y H:i:s')."</td>", "<td>".$res['address']."</td>", "<td>".$calltype."</td>", "<td>".str_pad($minutes, 2, "0", STR_PAD_LEFT).":".str_pad($seconds, 2, "0", STR_PAD_LEFT)."</td>", "<td>$money, руб.</td>";
- echo "</tr>";
- }
- echo "</table>", "<br>";
- $total = 1; //1 - выводить текст "Страница N из N", 0 - не выводить
- $a['mid_size'] = 3; //сколько ссылок показывать слева и справа от текущей
- $a['end_size'] = 1; //сколько ссылок показывать в начале и в конце
- $a['prev_text'] = '«'; //текст ссылки "Предыдущая страница"
- $a['next_text'] = '»'; //текст ссылки "Следующая страница"
- if ($max > 1) echo '<div class="navigation">';
- if ($total == 1 && $max > 1) $pages = '<span class="pages">Страница ' . $current . ' из ' . $max . '</span>'."<br>";
- echo $pages . paginate_links($a);
- if ($max > 1) echo '</div>';
- }
- } else {
- echo "Для просмотра статистики необходимо авторизоваться, нажав кнопку 'Войти'";
- }
- $output_string=ob_get_contents();;
- ob_end_clean();
- return $output_string;
- }
- function show_balance(){
- ob_start();
- if ( is_user_logged_in() ) {
- $user = wp_get_current_user();
- $balance = get_the_author_meta("balance", $user->ID );
- $balance = round((float)$balance, 2);
- echo "Баланс: ", esc_attr($balance), "<br/>", "<hr>";
- }
- $output_string=ob_get_contents();;
- ob_end_clean();
- return $output_string;
- }
- function get_payments(){
- ob_start();
- if ( is_user_logged_in() ) {
- global $wpdb;
- $user = wp_get_current_user();
- $table_payments = $wpdb->prefix.users_payments;
- $user_paymants = $wpdb->get_results(
- "
- SELECT * FROM $table_payments where (periodicity = '' or periodicity is null) and user_id = $user->ID
- ",
- "ARRAY_A"
- );
- echo "<table>";
- echo "<thead><tr><td>Дата платежа</td><td>Сумма</td><td>Назначение платежа</td></tr></thead>";
- foreach ($user_paymants as $user_paymant){
- echo "<tr><td>".$user_paymant["log_date"]."</td><td>".$user_paymant['summa']."</td><td>".$user_paymant['destination']."</td></tr>";
- };
- echo "</table>";
- }
- $output_string=ob_get_contents();;
- ob_end_clean();
- return $output_string;
- }
- function action_update(){
- echo "action update";
- }
- function edit_user_balance($user){
- if (current_user_can('administrator', $args)){
- $user_timezone = get_the_author_meta("user_timezone", $user->ID);
- echo "
- <h3>Баланс пользователя</h3>
- <table class='form-table'>
- <tr>
- <th><label for='balance_profile'>Баланс</label></th>
- <td>";
- echo esc_attr(round((float)get_the_author_meta("balance", $user->ID ), 2));
- echo "</td>
- </tr>
- </table>
- ";
- echo "
- <h3>Тариф пользователя</h3>
- <table class='form-table'>
- <tr>
- <th><label for='tarif_type_profile'>Тариф</label></th>
- <td>
- <select name='tarif_type_profile' required='required'>
- <option value=0 ".selected(get_the_author_meta("tarif_type", $user->ID ), 0, false).">Посекундная</option>
- <option value=1 ".selected(get_the_author_meta("tarif_type", $user->ID ), 1, false).">Поминутная</option>
- </select>
- </td>
- </tr>
- <tr>
- <th><label for='tarif_value_profile'>Цена</label></th>
- <td>
- <input type='number' name='tarif_value_profile' required='required' min='0' step='0.01' value='".get_the_author_meta("tarif_value", $user->ID )."'>
- </td>
- </tr>
- <tr>
- <th><label for='tarif_delay_sec_profile'>Не тарифицировать</label></th>
- <td>
- <input type='number' name='tarif_delay_sec_profile' required='required' min='0' step='1' value='".get_the_author_meta("tarif_delay_sec", $user->ID )."'>
- </td>
- </tr>
- <tr>
- <th><label for='user_timezone'>Часовой пояс</label></th>
- <td>
- <select name='user_timezone'>".wp_timezone_choice($user_timezone)."
- </select>
- </td>
- </tr>
- </table>
- ";
- $bee_login = get_the_author_meta("bee_login", $user->ID );
- $bee_pass = get_the_author_meta("bee_pass", $user->ID );
- echo "
- <h3>Настройка личного кабинета Билайн</h3>
- <table class='form-table'>
- <tr>
- <th><label for='bee_login'>Логин</label></th>
- <td>
- <input name='bee_login' value='".$bee_login."'>
- </td>
- </tr>
- <tr>
- <th><label for='bee_pass'>Цена</label></th>
- <td>
- <input name='bee_pass' value='".$bee_pass."'>
- </td>
- </tr>
- </table>
- ";
- };
- }
- function save_balance($user_id){
- update_user_meta($user_id, 'tarif_type', sanitize_text_field($_POST['tarif_type_profile']));
- update_user_meta($user_id, 'tarif_value', sanitize_text_field($_POST['tarif_value_profile']));
- update_user_meta($user_id, 'tarif_delay_sec', sanitize_text_field($_POST['tarif_delay_sec_profile']));
- update_user_meta($user_id, 'user_timezone', sanitize_text_field($_POST['user_timezone']));
- update_user_meta($user_id, 'bee_login', sanitize_text_field($_POST['bee_login']));
- update_user_meta($user_id, 'bee_pass', sanitize_text_field($_POST['bee_pass']));
- }
- function true_moi_interval( $raspisanie ) {
- // $raspisanie - это массив, состоящий из всех зарегистрированных интервалов
- // наша задача - добавить в него свой собственный интервал, к примеру пусть будет 3 минуты
- $raspisanie['ten_minute'] = array(
- 'interval' => 600, // в одной минуте 60 секунд, в 10 минутах - 600
- 'display' => 'Каждые 10 минут' // отображаемое имя
- );
- return $raspisanie;
- }
- function send_subscription(){
- global $wpdb;
- $table_accounts = $wpdb->prefix.users_accounts;
- $account_ids = $wpdb->get_results("SELECT id, custom_update FROM $table_accounts", "ARRAY_A");
- foreach ($account_ids as $account_id){
- if ($account_id["custom_update"] != 1){
- update_accounts($account_id["id"]);
- } else {
- $table_sips = $wpdb->prefix.users_accounts_sip;
- $array_sip = $wpdb->get_results($wpdb->prepare("SELECT sip FROM $table_sips where select_sip = 1 and users_accounts_id = %d", $account_id["id"]), "ARRAY_N");
- update_accounts($account_id["id"], $array_sip);
- }
- }
- }
- function show_user_info($content){
- if ( is_user_logged_in() ) {
- global $wpdb;
- $user = wp_get_current_user();
- return $user->display_name."<br/>".$user->description."<br/>".$content;
- } else {
- return $content;
- }
- }
- //Действия
- add_action('admin_menu', 'tatarnikov_add_admin_pages');
- add_action('admin_action_update', 'update', 'action_update');
- add_action('show_user_profile', 'edit_user_balance' );
- add_action('edit_user_profile', 'edit_user_balance' );
- add_action('edit_user_profile_update', 'save_balance' );
- add_action('personal_options_update', 'save_balance' );
- //add_action('the_content', 'show_user_info');
- //Шорткоды
- add_shortcode('statistics', 'get_statistics' );
- add_shortcode('balance', 'show_balance' );
- add_shortcode('payments', 'get_payments' );
- //Расписание
- add_filter('cron_schedules', 'true_moi_interval');
- add_action('send_subscription', 'send_subscription');
- if( !wp_next_scheduled('send_subscription'))
- wp_schedule_event(time(), 'ten_minute', 'send_subscription');
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement