· 6 years ago · Jun 18, 2019, 07:14 PM
1<?php
2require dirname( ABSPATH. WPINC ). '/vendor/autoload.php';
3
4// use Kreait\Firebase\Messaging\CloudMessage;
5// use Firebase\Auth\Token\Generator;
6// use Kreait\Firebase\Factory;
7// use Kreait\Firebase\ServiceAccount;
8// use Firebase\JWT\JWT;
9// use Firebase\Auth\Token\Verifier;
10// use Kreait\Firebase;
11use phpFCMv1\Client;
12use phpFCMv1\Config;
13use phpFCMv1\Notification;
14use phpFCMv1\Recipient;
15use phpFCMv1\Config\AndroidConfig;
16use phpFCMv1\Config\APNsCOnfig;
17/* ===============================
18==============================================
19 DEBUG OPTIONS
20 ========================================================================== */
21
22//ini_set( 'display_errors', 1 );
23//error_reporting( E_ERROR | E_WARNING | E_PARSE | E_NOTICE | E_STRICT );
24
25 //define('WLT_CUSTOMLOGINFORM', false);
26 //define('WLT_DEBUG_EMAIL', true);
27 //define('WLT_DEBUG_MOBILE', true);
28 //define('WLT_DEMOMODE',true);
29
30/* =============================================================================
31 LOAD IN FRAMEWORK
32 ========================================================================== */
33
34 // LOAD IN CLASS FILES
35 if(defined('TEMPLATEPATH') && !defined('THEME_VERSION') ){ include("framework/_config.php"); }
36
37/* =============================================================================
38 (AALHUTAMI CODE)
39 ========================================================================== */
40
41
42 add_action('wp_enqueue_scripts', 'my_register_javascript', 100);
43
44 function my_register_javascript() {
45 wp_register_script('mediaelement', plugins_url('wp-mediaelement.min.js', __FILE__), array('jquery'), '4.8.2', true);
46 wp_enqueue_script('mediaelement');
47 }
48
49 // get dashbord count
50 function getDashboardCountsForWeb($userid){
51 GLOBAL $wpdb;
52
53 $l=strlen($userid);
54 $str='"userid"';
55 $str2='"'.$userid.'"';
56 $userdata = get_userdata($userid);
57 $SQL="SELECT * FROM ".$wpdb->prefix."posts
58 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
59 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
60 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
61 AND mt2.meta_key = 'current_bid_data' and meta_value like '%".$str.";s:".$l.":".$str2.";%'";
62 $total_bids = $wpdb->get_results($SQL,ARRAY_A);
63
64 foreach ($total_bids as $key => $val){
65 $id = $total_bids[$key]['ID'];
66 $total_bids = getMetaNoFilter($id,$total_bids,$key);
67 if($total_bids[$key]['bidwinnerstring'] == $userdata->user_login){
68 unset($total_bids[$key]);
69 }
70 }
71
72 $total_bids_count = count($total_bids);
73
74
75 $SQL = "SELECT count(*) AS total_wins FROM ".$wpdb->prefix."posts
76 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
77 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
78 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
79 AND mt2.meta_key = 'bidwinnerstring' AND mt2.meta_value LIKE ('%-".$userid."-%')";
80 $total_wins = $wpdb->get_row($SQL);
81
82 $count_selling = $wpdb->get_row("SELECT DISTINCT (SELECT COUNT(*) FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$userid." AND post_status='publish' ) + (SELECT COUNT(*) FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$userid." AND post_status='pending') as total FROM ".$wpdb->prefix."posts");
83
84
85 $count_draft = $wpdb->get_results( "SELECT COUNT(*) as total_draft FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type'
86 AND p.post_status='draft' AND p.post_author=".$userid."");
87
88
89 $favlist = get_user_meta($userid,'favorite_list', true);
90 if(is_null($favlist) || empty($favlist)){
91 $favlist = 0;
92 }else{
93
94 $favlist = count($favlist);
95 }
96
97 $result = array();
98 $result['total_selling'] = $count_selling->total;
99 $result['total_draft'] = $count_draft[0]->total_draft;
100 $result['total_wins'] = $total_wins->total_wins;
101 $result['total_bids'] = $total_bids_count;
102 $result['total_fav'] = $favlist;
103
104 return $result;
105 }
106
107 // get dashboard draft
108 function getDraftAuctionsForWeb($user_id){
109 global $wpdb;
110 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type'
111 AND post_status = 'draft' AND p.post_author=".$user_id, ARRAY_A);
112 foreach ($result as $key => $val) {
113 $id = $result[$key]['ID'];
114 $result[$key]['categories']=getCategories($id);
115 $result = getMetaNoFilter($id,$result,$key);
116 }
117 usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
118 return $result;
119 }
120 //get total chat conversations
121 function getTotalChat($user_id){
122
123 global $wpdb;
124
125 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."chat_msg WHERE wp_chat_msg.user_to ='".$user_id."' or wp_chat_msg.user_from = '".$user_id . "' Group by (user_to)";
126 $wpdb->get_results($SQL_GETRATE);
127 return $wpdb->num_rows;
128 wp_die();
129 }
130 //get chat users list
131 function getChatUsers($user_id){
132
133 global $wpdb;
134
135 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."chat_msg WHERE user_to=".$user_id." or user_from =".$user_id . " Group by (user_to)";
136 $rows = $wpdb->get_results($SQL_GETRATE);
137 $item_row ='';
138 $counter = 0;
139 foreach ($rows as $user) {
140 $id = $user->user_to;
141 $user_info = get_userdata($id);
142 $user_img = get_user_meta($id,'userphoto', true);
143 if(is_array($user_img) && isset($user_img['path'])){
144 $user_photo = "<img style='width:64px;height:64px' src='".$user_img['img']."' class='avatar img-responsive' alt='image' />";
145 }else{
146 $user_photo = "<img style='width:64px;height:64px;' src='http://www.mazad-house.com/wp-content/uploads/no_profile_pic.png' class='avatar img-responsive' alt='image' />";
147 }
148 $item_row .= '<li style="cursor:pointer" onclick="loadChat(`'.$id . '|' . $user_id. '|' . $counter.'`)" class="list-group-item col-md-12 col-sm-12 col-xs-12" >';
149 $item_row .= '<div class="col-md-5">';
150 $item_row .= $user_photo;
151 $item_row .= '</div>';
152 $item_row .= '<div class="col-md-7">';
153 $item_row .= '<span class="text-center username" style="font-size:20px;">' . $user_info->user_login . ' </span>';
154 $item_row .= '</div>';
155 $item_row .= '</li>';
156 $counter = $counter + 1;
157 }
158 return $item_row;
159 wp_die();
160 }
161
162 //get chat conversation
163 function load_chat_ajax_handler(){
164 global $wpdb;
165 $user_from = $_POST['user_from'];
166 $user_to = $_POST['user_to'];
167 $current_user = wp_get_current_user();
168 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."chat_msg WHERE (user_to=".$user_from ." and user_from =".$user_to . ") or (user_to=".$user_to." and user_from =".$user_from . ") ORDER BY `message_date` ASC";
169 $rows = $wpdb->get_results($SQL_GETRATE);
170 $chat_body = '';
171 $currentL = weglot_get_current_language();
172 foreach ($rows as $user) {
173 $from_id = $user->user_from;
174 $to_id = $user->user_to;
175 $message = $user->message;
176 $message_date = $user->message_date;
177 if($currentL == 'en'){
178 if($from_id == $current_user->ID){
179 $chat_body .= "<div class='bot-message'><span>". $message_date ."
180 <div class='message no_translate'>" .$message . "</div>
181 </span></div>";
182 }
183 else{
184 $chat_body .= "<div class='user-message'>
185 <div class='message no_translate'>" .$message . "</div><span>". $message_date ."
186 </span></div>";
187 }
188 }else{
189 if($from_id == $current_user->ID){
190 $chat_body .= "<div class='bot-message'>
191 <div class='message no_translate'>" .$message . "</div><span>". $message_date ."
192 </span></div>";
193 }
194 else{
195 $chat_body .= "<div class='user-message'><span>". $message_date ."
196 <div class='message no_translate'>" .$message . "</div>
197 </span></div>";
198 }
199 }
200 }
201 echo $chat_body;
202 wp_die();
203 }
204 add_action('wp_ajax_load_chat', 'load_chat_ajax_handler');
205
206
207 //add chat message conversation
208 function add_chat_ajax_handler(){
209 global $wpdb;
210 $user_to = $_POST['user_to'];
211 $message = $_POST['message'];
212 print_r($_POST);
213 $current_user = wp_get_current_user();
214 $wpdb->insert('wp_chat_msg', array(
215 'user_to' => $user_to,
216 'user_from' => $current_user->ID,
217 'message' => $message,
218 'message_date' => current_time('mysql', 1),
219 'was_read' => '0',
220 ));
221 $lastid = $wpdb->insert_id;
222
223 //send push on message from chat
224
225 //take avatar
226 $user_img = get_user_meta($current_user->ID,'userphoto', true);
227 if(is_array($user_img) && isset($user_img['path'])){
228 $user_img_path = $user_img['img'];
229 }else{
230 $user_img_path = 'http://www.mazad-house.com/wp-content/uploads/no_profile_pic.png';
231 }
232
233 //take nickname
234 $nickname=get_user_meta($current_user->ID,'nickname',true);
235
236 $notification_body = array(
237 "auction" =>NULL,
238 "chat" => array (
239 "last_message" => $message,
240 "last_message_date" => current_time('mysql', 1),
241 "companion" => $current_user->ID,
242 "companion_avatar" => $user_img_path,
243 "companion_username" => $nickname
244 ) ,
245 );
246 //push user to
247 $notification_user_id = $user_to;
248 //push title
249 $notification_title = 'Last Message';
250 //push body
251 $endconded_body = json_encode($notification_body);
252 //use method for pushApi
253 $response = sendPushP($notification_user_id, $notification_title, $notification_body);
254 $encoded_response = json_encode($response);
255
256 echo $lastid;
257
258 wp_die();
259 }
260 add_action('wp_ajax_add_chat', 'add_chat_ajax_handler');
261
262 //search for user by name
263 function search_user_ajax_handler(){
264 global $wpdb;
265 $search_term = $_POST['term'];
266 $current_user = wp_get_current_user();
267 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."users WHERE user_login LIKE '" . $search_term . "%' AND ID <> " . $current_user->ID ;
268 $rows = $wpdb->get_results($SQL_GETRATE);
269 $items = array();
270 foreach ($rows as $user) {
271 $user_img = get_user_meta($user->ID,'userphoto', true);
272 if(is_array($user_img) && isset($user_img['path'])){
273 $user_img_path = $user_img['img'];
274 }else{
275 $user_img_path = 'http://www.mazad-house.com/wp-content/uploads/no_profile_pic.png';
276 }
277 $items[] = array(
278 'text' => $user->user_login,
279 'id' => $user->ID,
280 'img_path' => $user_img_path
281 );
282 }
283 echo json_encode($items);
284 wp_die();
285 }
286 add_action('wp_ajax_search_user', 'search_user_ajax_handler');
287
288 //search for user by id
289 function search_user_id_ajax_handler(){
290 global $wpdb;
291 $search_term = $_POST['term'];
292 $current_user = wp_get_current_user();
293 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."users WHERE ID = '" . $search_term . "' AND ID <> " . $current_user->ID ;
294 $rows = $wpdb->get_results($SQL_GETRATE);
295 $items = array();
296 foreach ($rows as $user) {
297 $user_img = get_user_meta($user->ID,'userphoto', true);
298 if(is_array($user_img) && isset($user_img['path'])){
299 $user_img_path = $user_img['img'];
300 }else{
301 $user_img_path = 'http://www.mazad-house.com/wp-content/uploads/no_profile_pic.png';
302 }
303 $items[] = array(
304 'text' => $user->user_login,
305 'id' => $user->ID,
306 'img_path' => $user_img_path
307 );
308 }
309 echo json_encode($items);
310 wp_die();
311 }
312 add_action('wp_ajax_search_user_id', 'search_user_id_ajax_handler');
313 function get_cities_list_ajax_handler() {
314 global $wpdb;
315
316 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."cities WHERE country_id = '1' AND status = '1'";
317 $rows = $wpdb->get_results($SQL_GETRATE);
318 $currentL = weglot_get_current_language();
319 $items = '';
320 foreach ($rows as $city) {
321 $id = $city->ID;
322 $name_ar = $city->name_ar;
323 $name_en = $city->name_en;
324 if($currentL == 'en'){
325 $items .= '<option class="no_translate" value="' . $id . '">'. $name_en .'</option>';
326 } else{
327 $items .= '<option class="no_translate" value="' . $id . '">'. $name_ar .'</option>';
328 }
329
330 }
331 echo $items;
332 wp_die();
333 }
334 add_action('wp_ajax_get_cities_list', 'get_cities_list_ajax_handler');
335
336
337
338
339 function get_countries_list_ajax_handler() {
340 global $wpdb;
341
342 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."countries WHERE ID = '1' AND status = '1'";
343 $rows = $wpdb->get_results($SQL_GETRATE);
344 $currentL = weglot_get_current_language();
345 $items = '';
346 foreach ($rows as $city) {
347 $id = $city->ID;
348 $name_ar = $city->name_ar;
349 $name_en = $city->name_en;
350 if($currentL == 'en'){
351 $items .= '<option class="no_translate" value="' . $id . '">'. $name_en .'</option>';
352 } else{
353 $items .= '<option class="no_translate" value="' . $id . '">'. $name_ar .'</option>';
354 }
355
356 }
357 echo $items;
358 wp_die();
359 }
360 add_action('wp_ajax_get_countries_list', 'get_countries_list_ajax_handler');
361
362 add_action('init','possibly_redirect');
363
364 function possibly_redirect(){
365 global $pagenow;
366 if( 'wp-login.php' == $pagenow ) {
367 wp_redirect('log-in/?login=true');
368 exit();
369 }
370 }
371
372 function updateExpiryDate($ID, $post ) {
373 $listing_expiry_days = get_post_meta( $ID, 'listing_expiry_days', true );
374 $listing_expiry_date = get_post_meta( $ID, 'listing_expiry_date', true );
375 $new_date = date('Y-m-d H:i:s', strtotime('+'.$listing_expiry_days.' days'));
376 update_post_meta( $ID, 'listing_expiry_date', $new_date );
377
378 $notification_user_id = $post->post_author;
379 $lang_user=get_user_meta($notification_user_id,'language',true);
380 $notification_body = '';
381 $notification_title = '';
382 if($lang_user=="EN"){
383 $notification_body = GetNotificationMessageForAuction($ID, NULL, "Your Auction has Been Approved",
384 NULL, "Auction Approved", "Auction name (EN)") ;
385 }
386 else {
387 $notification_body = GetNotificationMessageForAuction($ID, NULL,
388 "لقد تم اعتماد المزاد من قبل الادارة",
389 NULL, "مزاد معتمد', 'Auction name (AR)") ;
390 }
391
392 sendPushP($notification_user_id, $notification_title, $notification_body);
393 //echo "<script type='text/javascript'>alert('$notification_user_id $notification_body $notification_title');</script>";
394 }
395 add_action( 'publish_listing_type', 'updateExpiryDate', 10, 2 );
396
397 function get_cities_list(WP_REST_Request $request) {
398 global $wpdb;
399
400 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."cities WHERE country_id = '1' AND status = '1'";
401 $rows = $wpdb->get_results($SQL_GETRATE);
402 $currentL = weglot_get_current_language();
403 $items = '';
404 foreach ($rows as $city) {
405 $id = $city->ID;
406 $name_ar = $city->name_ar;
407 $name_en = $city->name_en;
408 if($currentL == 'en'){
409 $items .= '<option class="no_translate" value="' . $id . '">'. $name_en .'</option>';
410 } else{
411 $items .= '<option class="no_translate" value="' . $id . '">'. $name_ar .'</option>';
412 }
413
414 }
415 return $items;
416 wp_die();
417 }
418 function get_countries_list(WP_REST_Request $request) {
419 global $wpdb;
420
421 $SQL_GETRATE = "SELECT * FROM ".$wpdb->prefix."countries WHERE ID = '1' AND status = '1'";
422 $rows = $wpdb->get_results($SQL_GETRATE);
423 $currentL = weglot_get_current_language();
424 $items = '';
425 foreach ($rows as $city) {
426 $id = $city->ID;
427 $name_ar = $city->name_ar;
428 $name_en = $city->name_en;
429 if($currentL == 'en'){
430 $items .= '<option class="no_translate" value="' . $id . '">'. $name_en .'</option>';
431 } else{
432 $items .= '<option class="no_translate" value="' . $id . '">'. $name_ar .'</option>';
433 }
434
435 }
436 return $items;
437 wp_die();
438 }
439
440
441/* =============================================================================
442 ELATE API (D.Khodosok 2018)
443 ========================================================================== */
444 add_action( 'rest_api_init', 'wpc_register_wp_api_endpoints' );
445
446 function wpc_register_wp_api_endpoints() {
447
448 register_rest_route( 'elate-api/v1', '/getAllAucs/(?P<offset>\d+)', array(
449 'methods' => 'GET',
450 'callback' => 'getAllAuctions',
451 // 'permission_callback' => function ($request) {
452 // if (current_user_can('read'))
453 // return true; }
454 ));
455
456 //aalhutami code .. PLEASE DO NOT DELETE
457 register_rest_route( 'elate-api/v1', '/getAccessToken', array(
458 'methods' => 'GET',
459 'callback' => 'getAccessToken',
460 ));
461 register_rest_route( 'kaysih-api/v1', '/get_cities_list', array(
462 'methods' => 'GET',
463 'callback' => 'get_cities_list',
464 ));
465 register_rest_route( 'kaysih-api/v1', '/get_countries_list', array(
466 'methods' => 'GET',
467 'callback' => 'get_countries_list',
468 ));
469
470 register_rest_route( 'elate-api/v1', '/getFeatured/(?P<offset>\d+)', array(
471 'methods' => 'GET',
472 'callback' => 'getFeatured',
473 ));
474 register_rest_route( 'elate-api/v1', '/getLatest', array(
475 'methods' => 'GET',
476 'callback' => 'getLatest',
477 ));
478 register_rest_route( 'elate-api/v1', '/getSingleAuction/(?P<id>\d+)/(?P<shouldIncrement>\d+)', array(
479 'methods' => 'GET',
480 'callback' => 'getSingleAuction',
481 ));
482 register_rest_route( 'elate-api/v1', '/getAllTerms', array(
483 'methods' => 'GET',
484 'callback' => 'getAllTerms',
485 ));
486 register_rest_route( 'elate-api/v1', '/addToFavoritesList/(?P<uid>\d+)/(?P<auctionid>\d+)', array(
487 'methods' => 'GET',
488 'callback' => 'addToFavoritesList',
489 ));
490 register_rest_route( 'elate-api/v1', '/deleteFromFavorites/(?P<uid>\d+)/(?P<auctionid>\d+)', array(
491 'methods' => 'GET',
492 'callback' => 'deleteFromFavorites',
493 ));
494 register_rest_route( 'elate-api/v1', '/getEndingAuctions/(?P<offset>\d+)', array(
495 'methods' => 'GET',
496 'callback' => 'getEndingAuctions',
497 ));
498 register_rest_route( 'elate-api/v1', '/setBid/(?P<auctionid>\d+)/(?P<price>\d+)', array(
499 'methods' => 'POST',
500 'callback' => 'setBid',
501 ));
502 register_rest_route( 'elate-api/v1', '/buyNow/(?P<auctionid>\d+)', array(
503 'methods' => 'POST',
504 'callback' => 'buyNow',
505 ));
506 register_rest_route( 'elate-api/v1', '/login/', array(
507 'methods' => 'POST',
508 'callback' => 'login',
509 ));
510 register_rest_route( 'elate-api/v1', '/retrievepassword/', array(
511 'methods' => 'POST',
512 'callback' => 'password_retrieve',
513 ));
514
515 register_rest_route( 'elate-api/v1', '/signup/', array(
516 'methods' => 'POST',
517 'callback' => 'signup',
518 ));
519 register_rest_route( 'elate-api/v1', '/updateUserSocialMedia/', array(
520 'methods' => 'POST',
521 'callback' => 'updateUserSocialMedia',
522 ));
523 register_rest_route( 'elate-api/v1', '/userinfo/(?P<uid>\d+)', array(
524 'methods' => 'GET',
525 'callback' => 'getUserInfo',
526 ));
527
528 register_rest_route( 'elate-api/v1', '/getFavorites/(?P<uid>\d+)', array(
529 'methods' => 'GET',
530 'callback' => 'getFavorites',
531 ));
532 register_rest_route( 'elate-api/v1', '/validatecode/', array(
533 'methods' => 'POST',
534 'callback' => 'validateCode',
535 ));
536 register_rest_route( 'elate-api/v1', '/deleteAuction', array(
537 'methods' => 'POST',
538 'callback' => 'deleteAuction',
539 ));
540 register_rest_route( 'elate-api/v1', '/getAuctBySubcategory/(?P<categoryid>\d+)/(?P<offset>\d+)', array(
541 'methods' => 'GET',
542 'callback' => 'auctionsBySubcategory',
543 ));
544 register_rest_route( 'elate-api/v1', '/searchByName/', array(
545 'methods' => 'POST',
546 'callback' => 'auctionsByName',
547 ));
548
549
550 register_rest_route( 'elate-api/v1', '/searchFilter/', array(
551 'methods' => 'POST',
552 //'callback' => 'searchFilter',
553 'callback' => 'customSearch',
554 ));
555
556 register_rest_route( 'elate-api/v1', '/addNewAuction/', array(
557 'methods' => 'POST',
558 'callback' => 'addNewAuction',
559 ));
560
561 register_rest_route( 'elate-api/v1', '/isFavorite/(?P<uid>\d+)/(?P<auctionid>\d+)', array(
562 'methods' => 'GET',
563 'callback' => 'isFavorite',
564 ));
565 register_rest_route( 'elate-api/v1', '/getDashboardCounts/(?P<uid>\d+)', array(
566 'methods' => 'GET',
567 'callback' => 'getDashboardCounts',
568 ));
569
570 register_rest_route( 'elate-api/v1', '/getDashboardSellingCounts/(?P<uid>\d+)', array(
571 'methods' => 'GET',
572 'callback' => 'getDashboardSellingCounts',
573 ));
574
575 register_rest_route( 'elate-api/v1', '/getWonAucs/(?P<uid>\d+)/(?P<offset>\d+)', array(
576 'methods' => 'GET',
577 'callback' => 'getWonAucs',
578 ));
579 register_rest_route( 'elate-api/v1', '/getBidAucs/(?P<uid>\d+)/(?P<offset>\d+)', array(
580 'methods' => 'GET',
581 'callback' => 'getBidAucs',
582 ));
583
584 register_rest_route( 'elate-api/v1', '/updateUserPassword/', array(
585 'methods' => 'POST',
586 'callback' => 'updateUserPassword',
587 ));
588
589 register_rest_route( 'elate-api/v1', '/getAllAucsByUserId/(?P<uid>\d+)/(?P<offset>\d+)', array(
590 'methods' => 'GET',
591 'callback' => 'getAllAucsByUserId',
592 ));
593
594 register_rest_route( 'elate-api/v1', '/getSoldAucsByUserId/(?P<uid>\d+)', array(
595 'methods' => 'GET',
596 'callback' => 'getSoldAucsByUserId',
597 ));
598 register_rest_route( 'elate-api/v1', '/getBankInfo/(?P<uid>\d+)', array(
599 'methods' => 'GET',
600 'callback' => 'getBankInfo',
601 ));
602 register_rest_route( 'elate-api/v1', '/updateBankInfo', array(
603 'methods' => 'POST',
604 'callback' => 'updateBankInfo',
605 ));
606
607 register_rest_route( 'elate-api/v1', '/updatePhoneNumber', array(
608 'methods' => 'POST',
609 'callback' => 'updatePhoneNumber',
610 ));
611
612 register_rest_route( 'elate-api/v1', '/validateCodeUpdate', array(
613 'methods' => 'POST',
614 'callback' => 'validateCodeUpdate',
615 ));
616 register_rest_route( 'elate-api/v1', '/updateUserInfo', array(
617 'methods' => 'POST',
618 'callback' => 'updateUserInfo',
619 ));
620 register_rest_route( 'elate-api/v1', '/updateUserPhoto', array(
621 'methods' => 'POST',
622 'callback' => 'updateUserPhoto',
623 ));
624 register_rest_route( 'elate-api/v1', '/removeUserPhoto/(?P<uid>\d+)', array(
625 'methods' => 'GET',
626 'callback' => 'removeUserPhoto',
627 ));
628 register_rest_route( 'elate-api/v1', '/getUsersFeedbacks/(?P<uid>\d+)', array(
629 'methods' => 'GET',
630 'callback' => 'getUsersFeedbacks',
631 ));
632 register_rest_route( 'elate-api/v1', '/getUsersSentFeedbacks/(?P<uid>\d+)', array(
633 'methods' => 'GET',
634 'callback' => 'getUsersSendedFeedbacks',
635 ));
636
637 register_rest_route( 'elate-api/v1', '/removeUserPhoto/(?P<uid>\d+)/', array(
638 'methods' => 'GET',
639 'callback' => 'removeUserPhoto',
640 ));
641
642 register_rest_route( 'elate-api/v1', '/getSellingAucsByUserId/(?P<uid>\d+)/(?P<offset>\d+)', array(
643 'methods' => 'GET',
644 'callback' => 'getSellingAucsByUserId',
645 ));
646
647 register_rest_route( 'elate-api/v1', '/getSellingPendingAucsByUserId/(?P<uid>\d+)/(?P<offset>\d+)', array(
648 'methods' => 'GET',
649 'callback' => 'getSellingPendingAucsByUserId',
650 ));
651
652 register_rest_route( 'elate-api/v1', '/getSellingSoldAucsByUserId/(?P<uid>\d+)/(?P<offset>\d+)', array(
653 'methods' => 'GET',
654 'callback' => 'getSellingSoldAucsByUserId',
655 ));
656
657 register_rest_route( 'elate-api/v1', '/getSellingNotSoldAucsByUserId/(?P<uid>\d+)/(?P<offset>\d+)', array(
658 'methods' => 'GET',
659 'callback' => 'getSellingNotSoldAucsByUserId',
660 ));
661
662 register_rest_route( 'elate-api/v1', '/getSellingCurrentAucsByUserId/(?P<uid>\d+)/(?P<offset>\d+)', array(
663 'methods' => 'GET',
664 'callback' => 'getSellingCurrentAucsByUserId',
665 ));
666
667
668
669 register_rest_route( 'elate-api/v1', '/getEnchacementsPrice/', array(
670 'methods' => 'GET',
671 'callback' => 'getEnchacementsPrice',
672 ));
673 register_rest_route( 'elate-api/v1', '/getWinAucsForFeedback/(?P<uid>\d+)', array(
674 'methods' => 'GET',
675 'callback' => 'getWinAucsForFeedback',
676 ));
677
678 register_rest_route( 'elate-api/v1', '/sendpush', array(
679 'methods' => 'POST',
680 'callback' => 'sendP',
681 ));
682
683 register_rest_route( 'elate-api/v1', '/sendpushp', array(
684 'methods' => 'POST',
685 'callback' => 'sendPushP',
686 ));
687
688
689 register_rest_route( 'elate-api/v1', '/addFeedBack', array(
690 'methods' => 'POST',
691 'callback' => 'addFeedBack',
692 ));
693
694 register_rest_route( 'elate-api/v1', '/addDeviceToken', array(
695 'methods' => 'POST',
696 'callback' => 'addDeviceToken',
697 ));
698
699 register_rest_route( 'elate-api/v1', '/getAllActiveCities', array(
700 'methods' => 'GET',
701 'callback' => 'getAllActiveCities',
702 ));
703
704
705 register_rest_route( 'elate-api/v1', '/getAllActiveCountries', array(
706 'methods' => 'GET',
707 'callback' => 'getAllActiveCountries',
708 ));
709
710 register_rest_route( 'elate-api/v1', '/getCitiesByCountryId/(?P<countryid>\d+)', array(
711 'methods' => 'GET',
712 'callback' => 'getCitiesByCountryId',
713 ));
714
715 register_rest_route( 'elate-api/v1', '/getCountryById/(?P<countryid>\d+)', array(
716 'methods' => 'GET',
717 'callback' => 'getCountryById',
718 ));
719
720 register_rest_route( 'elate-api/v1', '/editAuction/', array(
721 'methods' => 'POST',
722 'callback' => 'editAuction',
723 ));
724
725
726
727
728 register_rest_route( 'elate-api/v1', '/relistAuction/(?P<uid>\d+)/(?P<auctionid>\d+)', array(
729 'methods' => 'GET',
730 'callback' => 'relistAuction',
731 ));
732
733 register_rest_route( 'elate-api/v1', '/setDraftToPending/(?P<id>\d+)', array(
734 'methods' => 'GET',
735 'callback' => 'setDraftAuctionsToPending',
736 ));
737
738
739 register_rest_route( 'elate-api/v1', '/addDraftAuction/', array(
740 'methods' => 'POST',
741 'callback' => 'addDraftAuction',
742 ));
743
744
745
746 register_rest_route( 'elate-api/v1', '/getDraftAuctions/(?P<uid>\d+)/(?P<offset>\d+)', array(
747 'methods' => 'GET',
748 'callback' => 'getDraftAuctions',
749 ));
750
751
752 register_rest_route( 'elate-api/v1', '/getLastChatMessage/(?P<uid>\d+)', array(
753 'methods' => 'GET',
754 'callback' => 'getLastChatMessage',
755 ));
756
757 register_rest_route( 'elate-api/v1', '/getLastChatMessageNew/(?P<uid>\d+)', array(
758 'methods' => 'GET',
759 'callback' => 'getLastChatMessageNew',
760 ));
761
762
763 register_rest_route( 'elate-api/v1', '/findUser', array(
764 'methods' => 'POST',
765 'callback' => 'findUserByUsername',
766 ));
767
768
769
770 register_rest_route( 'elate-api/v1', '/getPaymentInfo/(?P<uid>\d+)', array(
771 'methods' => 'GET',
772 'callback' => 'getPaymentInfo',
773 ));
774
775 register_rest_route( 'elate-api/v1', '/payModal/', array(
776 'methods' => 'POST',
777 'callback' => 'payModal',
778 ));
779 register_rest_route( 'elate-api/v1', '/payTabs/', array(
780 'methods' => 'GET',
781 'callback' => 'payTabs',
782 ));
783 register_rest_route( 'elate-api/v1', '/getOptions/', array(
784 'methods' => 'GET',
785 'callback' => 'getOptions',
786 ));
787
788 register_rest_route( 'elate-api/v1', '/updateFeatures/', array(
789 'methods' => 'POST',
790 'callback' => 'updateFeatures',
791 ));
792
793 register_rest_route( 'elate-api/v1', '/setLanguage/', array(
794 'methods' => 'POST',
795 'callback' => 'setLanguage',
796 ));
797
798
799
800 }
801
802function getAccessToken(WP_REST_Request $request){
803 global $CORE, $wpdb;
804 $token = bin2hex(random_bytes(16));
805 $version = phpversion();
806 return $token;
807
808 }
809
810 function updateFeatures(WP_REST_Request $request){
811 global $CORE, $wpdb;
812 $auctionId = $request["auctionid"];
813 $featuredAuction=$request['featuredauction'];
814 $Html=$request['supporthtml'];
815 $topCategory=$request['topCategory'];
816
817 update_post_meta($auctionId,'featured',$featuredAuction);
818 update_post_meta($auctionId,'html',$Html);
819 update_post_meta($auctionId,'topcategory',$topCategory);
820
821 $result['featuredAuction']=get_post_meta($auctionId,'featured',true);
822 $result['supportHTML']=get_post_meta($auctionId,'html',true);
823 $result['topCategory']=get_post_meta($auctionId,'topcategory',true);
824
825 return $result;
826
827 }
828
829
830 function payModal(WP_REST_Request $request){
831
832 global $CORE, $wpdb;
833 $userId = $request["userid"];
834 if(verifyToken($userId)){
835 $auctionId = $request["auctionid"];
836 $deviceToken=$request["devicetoken"];
837 $total=get_post_meta( $auctionId,'listing_price',true);
838 $total= number_format(str_replace(",","",$total),2);
839 $total=strip_tags($total);
840 $item_name=get_post( $auctionId,'post_title',true);
841 $item_name=$item_name->post_title;
842 $item_name=strip_tags($item_name);
843 $return=$GLOBALS['CORE_THEME']['links']['callback'].'?auth=1';
844 $cansel_return=$GLOBALS['CORE_THEME']['links']['callback'];
845 $orderID= "LST-".$auctionId."-".$userId."-".date("Ymdhis");
846 $amount= strip_tags($total)/3.75;
847 $business=get_option('paypal_email');
848 $bn='PREMIUMPRESSLIMITED_SP';
849 if(!isset($GLOBALS['pformid'])){ $GLOBALS['pformid'] = 1; }else{ $GLOBALS['pformid']++; }
850 // $gatewaycode = "";
851 // $gatewaycode .= '<form method="post" style="margin:0px !important;" action="https://www.sandbox.paypal.com/cgi-bin/webscr" name="checkout_paypal'.$GLOBALS['pformid'].'">';
852 // $gatewaycode .= '
853 // <input type="hidden" name="rm" value="2">
854 // <input type="hidden" name="lc" value="'.get_option('paypal_language').'">
855 // <input type="hidden" name="return" value="'.$GLOBALS['CORE_THEME']['links']['callback'].'?auth=1">
856 // <input type="hidden" name="cancel_return" value="'.$GLOBALS['CORE_THEME']['links']['callback'].'">
857 // <input type="hidden" name="notify_url" value="'.$GLOBALS['CORE_THEME']['links']['callback'].'">';
858 // if(isset($GLOBALS['discount']) && strlen($GLOBALS['discount']) > 0){
859 // $gatewaycode .= '<input type="hidden" name="discount_amount_cart" value="'.trim($GLOBALS['discount']).'">';
860 // }
861 // $gatewaycode .= '<input type="hidden" name="cmd" value="_xclick">';
862 // $gatewaycode .= '<input type="hidden" name="amount" value="'.strip_tags($total).'" id="paypalAmount">';
863 // $gatewaycode .= '<input type="hidden" name="item_name" value="'.strip_tags($item_name).'">';
864 //
865 // $gatewaycode .= '
866 // <input type="hidden" name="item_number" value="'.$orderID.'">
867 // <input type="hidden" name="business" value="'.get_option('paypal_email').'">
868 // <input type="hidden" name="currency_code" value="'.hook_price_currencycode(get_option('paypal_currency')).'">
869 // <input type="hidden" name="charset" value="utf-8">
870 // <input type="hidden" name="custom" value="'.$orderID.'" class="paymentcustomfield">
871 // <input type="hidden" name="bn" value="PREMIUMPRESSLIMITED_SP">
872 // './/'<button class="btn btn-lg btn-info">'.$CORE->_e(array('button','21')).'</button>'.'</form>';
873 // MakePayButton('javascript:document.checkout_paypal'.$GLOBALS['pformid'].'.submit();').'</form>';
874
875
876 $Curl = curl_init();
877 curl_setopt_array($Curl, array(
878 CURLOPT_URL => 'https://www.sandbox.paypal.com/cgi-bin/webscr',
879 CURLOPT_RETURNTRANSFER => true,
880 CURLOPT_POST => true,
881 CURLOPT_POSTFIELDS => http_build_query(array('rm' => '2',
882 'lc' => 'US',
883 'return' => "$return",
884 'cancel_return' => "$cansel_return",
885 'notify_url' => "$cansel_return",
886 'discount_amount_cart' => '0',
887 'cmd' => '_xclick',
888 'amount' => "$amount",
889 'item_name' => "$total",
890 'item_number' => "$orderID",
891 'business' => "$business",
892 'currency_code' => 'USD',
893 'charset' => 'utf-8',
894 'custom' => "$orderID",
895 'bn' => "$bn"))
896 ));
897
898 $response = curl_exec($Curl);
899 curl_close($Curl);
900
901 if($url = preg_match('~(https|ftp|telnet)(://)(.*)~', $response, $match))
902 {
903 $request=$match['1'].$match['2'].$match['3'];
904 }
905
906 return $request;
907 }
908 else {
909 return 'Access error!';
910 }
911 }
912
913 function payTabs(WP_REST_Request $request){
914 global $CORE, $wpdb;
915
916 $userId = $request["userid"];
917 if(verifyToken($userId)){
918 $auctionId = $request["auctionid"];
919 $total=get_post_meta( $auctionId,'listing_price',true);
920 $total= number_format(str_replace(",","",$total),2);
921 $total=strip_tags($total);
922 $item_name=get_post( $auctionId,'post_title',true);
923 $item_name=$item_name->post_title;
924 $item_name=strip_tags($item_name);
925 $return= "http://www.kayish.com/wp-json/elate-api/v1/paytabs_callback";//$GLOBALS['CORE_THEME']['links']['callback'];
926 $cansel_return=$GLOBALS['CORE_THEME']['links']['callback'];
927 $orderID= "LST-".$auctionId."-".$userId."-".date("Ymdhis");
928 $amount=strip_tags($total);
929 $user_info = get_userdata($userId);
930 if(isset($user_info->first_name) && strlen( $user_info->first_name) > 1){
931 $first_name = $user_info->first_name;
932 }else{
933 $first_name = 'Kayish';
934 }
935 if(isset($user_info->last_name) && strlen( $user_info->last_name) > 1){
936 $last_name = $user_info->last_name;
937 }else{
938 $last_name = 'User';
939 }
940 $full_name = $first_name . ' ' . $last_name;
941 $email = $user_info->user_email;
942 $phone = get_user_meta($userId,'phone',true);
943 $phone = preg_replace('/^\+?1|\|1|\D/', '', ($phone));
944 $lang=$request["lang"];
945 if(!empty($lang) && $lang=="ENG"){
946 $lang = 'English';
947 }else{
948 $lang = 'Arabic';
949 }
950 $server_ip = $_SERVER['SERVER_ADDR'];
951
952 require_once 'paytabs/paytabs.php';
953
954 $pt = new paytabs("admin@kayish.com", "5UQqJBeUWiQtPnDPGImFIB69wNzk7AOdvEDegR8caZFZmiP31cIJNPTkCsEK2tXy7BMnsVzDUfChxslzE3isTcMvErgHUef2P1qi");
955 $payment_data = array(
956 "merchant_email" => "admin@kayish.com",
957 "secret_key" => "5UQqJBeUWiQtPnDPGImFIB69wNzk7AOdvEDegR8caZFZmiP31cIJNPTkCsEK2tXy7BMnsVzDUfChxslzE3isTcMvErgHUef2P1qi",
958 "site_url" => "http://www.kayish.com",
959 "return_url" => "http://www.kayish.com/paytab-callback/",
960 "title" => "$full_name",
961 "cc_first_name" => "$first_name",
962 "cc_last_name" => "$last_name",
963 "cc_phone_number" => "966",
964 "phone_number" => "$phone",
965 "email" => "$email",
966 "products_per_title" => "Auction Enhancement",
967 "unit_price" => "$total",
968 "quantity" => "1",
969 "other_charges" => "0",
970 "amount" => "$total",
971 "discount" => "0",
972 "currency" => "SAR",
973 "reference_no" => "$orderID",
974 "billing_address" => "Mazad House",
975 "city" => "Jeddah",
976 "state" => "Makkah",
977 "postal_code" => "12345",
978 "country" => "SAU",
979 "shipping_first_name" => "$first_name",
980 "shipping_last_name" => "$last_name",
981 "address_shipping" => "Mazad House",
982 "state_shipping" => "Makkah",
983 "city_shipping" => "Jeddah",
984 "postal_code_shipping" => "12345",
985 "country_shipping" => "SAU",
986 "msg_lang" => "$lang",
987 "cms_with_version" => "WordPress5.0-kayish",
988 "paypage_info" => "1");
989 $result = $pt->authentication();
990 $result = $pt->create_pay_page($payment_data);
991 $request = $result->payment_url;
992 return $request;
993 }
994 else
995 {
996 return 'Access error!';
997 }
998 }
999
1000 // function payTabs(WP_REST_Request $request){
1001 // global $CORE, $wpdb;
1002 // $userId = $request["userid"];
1003 // $auctionId = $request["auctionid"];
1004 // $lang=$request["lang"];
1005 // $post_param=get_post($auctionId,'post_type',true);
1006
1007 // if(!empty($lang) && $lang=="ENG")
1008 // {
1009 // $result="http://www.mazad-house.com/en/";
1010 // $result=$result."?post_type=".$post_param->post_type."&p=".$post_param->ID."&payment_redirect=PayTabs";
1011 // }
1012 // else {
1013 // $result=$post_param->guid;
1014 // $result=$result."&payment_redirect=PayTabs";
1015 // }
1016
1017
1018 // if($userId==$post_param->post_author)
1019 // {
1020 // return $result;
1021 // }
1022 // else
1023 // {
1024 // return "Access error!";
1025 // }
1026
1027
1028 // }
1029
1030 function getOptions(WP_REST_Request $request)
1031 {
1032 global $wpdb;
1033 $SQL = "SELECT * FROM ".$wpdb->prefix."options WHERE `option_id` = 9325";
1034 $result = $wpdb->get_results($SQL,ARRAY_A);
1035 $options=$result[0]['option_value'];
1036 return $options;
1037 }
1038
1039function updateUserPhoto(WP_REST_Request $request){
1040 global $CORE, $wpdb;
1041 $user_id = $request['uid'];
1042 if(verifyToken($user_id)){
1043 //die(var_dump($_FILES));
1044 if(isset($_FILES['wlt_userphoto']) && strlen($_FILES['wlt_userphoto']['name']) > 2 && in_array($_FILES['wlt_userphoto']['type'],$CORE->allowed_image_types) ){
1045
1046 // INCLUDE UPLOAD SCRIPTS
1047 if(!function_exists('wp_handle_upload')){
1048 $dir_path = str_replace("wp-content","",WP_CONTENT_DIR);
1049 require $dir_path . "/wp-admin/includes/file.php";
1050 }
1051
1052 // GET WORDPRESS UPLOAD DATA
1053 $uploads = wp_upload_dir();
1054
1055 // UPLOAD FILE
1056 $file_array = array(
1057 'name' => $_FILES['wlt_userphoto']['name'], //$userdata->ID."_userphoto",//
1058 'type' => $_FILES['wlt_userphoto']['type'],
1059 'tmp_name' => $_FILES['wlt_userphoto']['tmp_name'],
1060 'error' => $_FILES['wlt_userphoto']['error'],
1061 'size' => $_FILES['wlt_userphoto']['size'],
1062 );
1063 //die(print_r($file_array));
1064 $uploaded_file = wp_handle_upload( $file_array, array( 'test_form' => FALSE ));
1065
1066 // CHECK FOR ERRORS
1067 if(isset($uploaded_file['error']) ){
1068 $GLOBALS['error_message'] = $uploaded_file['error'];
1069 }else{
1070 // NOW LETS SAVE THE NEW ONE
1071 $result = update_user_meta($user_id, 'userphoto', array('img' => $uploads['url']."/".$file_array['name'], 'path' => $uploads['path']."/".$file_array['name'] ) );
1072 }
1073 if($result){
1074 $result = array('status' => 'success',
1075 'message' =>'Profile updated');
1076 return $result;
1077 }
1078 $result = array('status' => 'error',
1079 'message' =>'Unknown error');
1080 return $result;
1081
1082 }
1083 else
1084 {
1085 return "Access error!";
1086 }
1087 }
1088 }
1089
1090 function removeUserPhoto(WP_REST_Request $request){
1091 $userid = $request['uid'];
1092 if(verifyToken($userid)){
1093 $result = delete_user_meta($userid, 'userphoto');
1094 if($result){
1095 $result = array('status' => 'success',
1096 'message' =>'Profile updated');
1097 return $result;
1098 }
1099 $result = array('status' => 'error',
1100 'message' =>'Unknown error');
1101 return $result;
1102 }
1103 else {
1104 return "Access error!";
1105 }
1106 }
1107
1108 function updateUserInfo(WP_REST_Request $request){
1109 $userid = $request['uid'];
1110 if(verifyToken($userid)){
1111 $first_name = $request['first_name'];
1112 $last_name = $request['last_name'];
1113 $email = $request['email'];
1114 $country = $request['country'];
1115 $about = $request['about'];
1116
1117
1118 $user = get_user_by('email',$email);
1119 if($user && $user->data->ID != $userid){
1120 $result = array( 'status' => 'error', 'message' => 'This email is already registered. Please enter a new email');
1121 return $result;
1122 }else{
1123 $countryISO = getCountryISO($country);
1124 update_user_meta($userid, 'first_name', $first_name);
1125 update_user_meta($userid, 'last_name', $last_name);
1126 update_user_meta($userid, 'country', $countryISO);
1127 update_user_meta($userid, 'description', $about);
1128 update_user_meta($userid, 'email', $email);
1129 $result = wp_update_user(array( 'ID' => $userid, 'user_email' => $email));
1130 if($result){
1131 $result = array('status' => 'success',
1132 'message' =>'Profile updated');
1133 return $result;
1134 }
1135 else{
1136 $result = array('status' => 'error',
1137 'message' =>'Unknown error');
1138 return $result;
1139 }
1140 }
1141 }
1142 else {
1143 return 'Access error!';
1144 }
1145 }
1146
1147 function getCountryISO ($country){
1148 $result = file_get_contents("http://country.io/names.json");
1149 $value = json_decode($result);
1150 $array_value = (array) $value;
1151 $ISO = array_search($country, $array_value);
1152 return $ISO;
1153 }
1154
1155 function getCountryFull ($country){
1156 $result = file_get_contents("http://country.io/names.json");
1157 $value = json_decode($result);
1158 return $value->$country;
1159 }
1160
1161 function login(WP_REST_Request $request){
1162 $creds = array();
1163
1164 $creds['user_login'] = $request["username"];
1165 $creds['user_password'] = $request["password"];
1166 $language= $request["language"];
1167 $creds['remember'] = true;
1168 //Logic add meta token
1169 $user = wp_signon($creds, false );
1170 $userToken = $request["device_token"];
1171 $auth_verify=generateToken($user->data->ID);
1172 if ( is_wp_error($user) ){
1173 $result = array('status' => 'error',
1174 'message' =>'Incorrect login credentials, please try again' );
1175 return $result;
1176 }else{
1177 $rt = new WP_REST_Request('GET','/elate-api/v1/userInfo/'.$user->data->ID.'');
1178 $rsp = rest_do_request($rt);
1179 $rsp->data['auth-token']=$auth_verify;
1180 update_user_meta($user->data->ID,'language',$language);
1181 return $rsp;
1182 }
1183 }
1184
1185
1186 function updateUserPassword(WP_REST_Request $request){
1187 global $wpdb;
1188 $userId = $request['userId'];
1189 if(verifyToken($userId)){
1190 $oldpassword = $request['oldpassword'];
1191 $newpassword = $request['newpassword'];
1192 $newpassword_copy = $request['newpassword_copy'];
1193
1194 $creds = array();
1195 $user_info = get_userdata($userId);
1196 $creds['user_login'] = $user_info->user_login;
1197 $creds['user_password'] = $request['oldpassword'];
1198 $creds['remember'] = false;
1199 $session = wp_signon($creds, false);
1200 if ( is_wp_error($session) ){
1201 $result = array('status' => 'error',
1202 'message' =>'Incorrect user credentials' );
1203 return $result;
1204 }else{
1205 if($newpassword == $newpassword_copy){
1206 $result = wp_set_password( $newpassword, $userId);
1207 $result = array('status' => 'success',
1208 'message' =>'Password updated');
1209 }else{
1210 $result = array('status' => 'error',
1211 'message' =>'Passwords dont match');
1212 }
1213 }
1214 return $result;
1215 }
1216 else {
1217 return "Access error!";
1218 }
1219 }
1220
1221
1222function updateUserSocialMedia(WP_REST_Request $request){
1223 $user_id = $request['userid'];
1224 if(verifyToken($user_id)){
1225 $twitter = $request['twitter'];
1226 $skype = $request['skype'];
1227 $facebook = $request['facebook'];
1228 $linkedin = $request['linkedin'];
1229 update_user_meta($user_id, 'twitter', $twitter);
1230 update_user_meta($user_id, 'skype', $skype);
1231 update_user_meta($user_id, 'facebook', $facebook);
1232 update_user_meta($user_id, 'linkedin', $linkedin);
1233 $result = array('status' => 'success',
1234 'message' =>'Socialmedia updated');
1235 return $result;
1236 }
1237 else {
1238 return "Access error!";
1239 }
1240}
1241
1242function getRateByUserId($author_id){
1243 global $wpdb;
1244
1245 $SQL_GETRATE = "SELECT count(*) as total, sum(mt2.meta_value) AS total_score FROM ".$wpdb->prefix."posts INNER JOIN ".$wpdb->prefix."postmeta AS mt1 ON (".$wpdb->prefix."posts.ID = mt1.post_id ) INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id )
1246 WHERE 1=1
1247 AND ".$wpdb->prefix."posts.post_status = 'publish'
1248 AND mt1.meta_key = 'uid' AND mt1.meta_value = '".$author_id."' AND mt2.meta_key = 'score'";
1249 $rate = $wpdb->get_results($SQL_GETRATE);
1250 return $rate;
1251}
1252
1253
1254function getRate($post_id){
1255 global $wpdb;
1256 $author_id = get_post_field('post_author',$post_id);
1257 $SQL_GETRATE = "SELECT count(*) as total, sum(mt2.meta_value) AS total_score FROM ".$wpdb->prefix."posts INNER JOIN ".$wpdb->prefix."postmeta AS mt1 ON (".$wpdb->prefix."posts.ID = mt1.post_id ) INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id )
1258 WHERE 1=1
1259 AND ".$wpdb->prefix."posts.post_status = 'publish'
1260 AND mt1.meta_key = 'uid' AND mt1.meta_value = '".$author_id."' AND mt2.meta_key = 'score'";
1261 $rate = $wpdb->get_results($SQL_GETRATE);
1262
1263 return $rate;
1264}
1265
1266function getMetaFormated($id , $result, $key){
1267 global $wpdb;
1268 $result[$key]['listing_expiry_date'] = get_post_meta( $id,'listing_expiry_date',true);
1269 if($result[$key]['listing_expiry_date'] ==""){
1270 unset($result[$key]);
1271 return $result;
1272 };
1273
1274 $result[$key]['price_bin'] = get_post_meta( $id, 'price_bin', true );
1275 $result[$key]['price_current'] = get_post_meta( $id, 'price_current', true );
1276 $result[$key]['price_bin'] = get_post_meta( $id, 'price_bin', true );
1277 $result[$key]['city'] = get_post_meta( $id, 'city_id', true );
1278
1279 $city_id = get_post_meta( $id, 'city_id', true );
1280 $result[$key]['city'] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."cities WHERE ID = $city_id");
1281 $country_id = $result[$key]['city']->country_id;
1282 $result[$key]['country'] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."countries WHERE ID = $country_id");
1283
1284 $bid_array = get_post_meta( $id, 'current_bid_data', true );
1285 foreach ($bid_array as $dkey => $value) {
1286 $html=get_avatar($bid_array[$dkey]['userid']);
1287 $doc = new DOMDocument();
1288 $doc->loadHTML($html);
1289 $xpath = new DOMXPath($doc);
1290 $src = $xpath->evaluate("string(//img/@src)");
1291 $bid_array[$dkey]['avatar'] = $src;
1292 }
1293
1294 $result[$key]['current_bid_data'] = array_values($bid_array);
1295 $result[$key]['auction_type'] = get_post_meta( $id, 'auction_type', true );
1296 $result[$key]['price_reserve'] = get_post_meta( $id, 'price_reserve', true );
1297 $result[$key]['price_current'] = get_post_meta( $id, 'price_current', true );
1298 $result[$key]['price_shipping'] = get_post_meta( $id, 'price_shipping', true );
1299 $result[$key]['price_bin'] = get_post_meta( $id, 'price_bin', true );
1300 $result[$key]['condition'] = get_post_meta( $id, 'condition', true );
1301
1302 $rating = getRate($id);
1303 $result[$key]['total_rating'] = $rating[0]->total;
1304 if(is_null($rating[0]->total_score)){$rating[0]->total_score = (string)0;}
1305 $result[$key]['total_score'] = $rating[0]->total_score;
1306 if($rating[0]->total_score == 0){
1307 $result[$key]['star_rating'] = (string)0;
1308 }else{
1309 $result[$key]['star_rating'] = (string)($rating[0]->total_score/$rating[0]->total);
1310 }
1311
1312 $result[$key]['topcategory'] = get_post_meta( $id, 'topcategory', true );
1313 $result[$key]['featured'] = get_post_meta( $id, 'featured', true );
1314 $result[$key]['html'] = get_post_meta( $id, 'html', true );
1315 $result[$key]['listing_expiry_date'] = get_post_meta( $id,'listing_expiry_date',true);
1316 $result[$key]['listing_expiry_days'] = get_post_meta( $id,'listing_expiry_days',true);
1317 $result[$key]['hits'] = get_post_meta( $id, 'hits', true );
1318 $result[$key]['bidstring'] = get_post_meta( $id, 'bidstring', true );
1319 $userdata = get_userdata(preg_replace('![^0-9]+!', '', get_post_meta( $id, 'bidwinnerstring', true )));
1320 //$userdata = get_userdata(intval(preg_replace('![^0-9]+!','',preg_replace('/\d+/', '', get_post_meta( $id, 'bidwinnerstring', true ),1),1)));
1321
1322 $result[$key]['bidwinnerstring'] = $userdata->user_login;
1323 $result[$key]['image'] = get_post_meta( $id, 'image', true );
1324 $result[$key]['image_array'] = get_post_meta( $id, 'image_array', true);
1325 $result[$key]['video_array'] = get_post_meta( $id, 'video_array', true);
1326 $thumbnailID = get_post_meta( $id, '_thumbnail_id', true );
1327 $thumbnail = wp_get_attachment_image_src($thumbnailID, 'post' );
1328 $result[$key]['thumbnail'] = $thumbnail[0];
1329
1330 return $result;
1331}
1332
1333
1334function getMetaNoFilter($id , $result, $key){
1335 global $wpdb;
1336 $result[$key]['price_bin'] = get_post_meta( $id, 'price_bin', true );
1337 $result[$key]['price_current'] = get_post_meta( $id, 'price_current', true );
1338 $result[$key]['price_bin'] = get_post_meta( $id, 'price_bin', true );
1339 $result[$key]['listing_price_due'] = get_post_meta( $id, 'listing_price_due', true );
1340 $result[$key]['listing_price_paid'] = get_post_meta( $id, 'listing_price_paid', true );
1341
1342 $city_id = get_post_meta( $id, 'city_id', true );
1343 $result[$key]['city'] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."cities WHERE ID = $city_id");
1344
1345 $country_id = $result[$key]['city']->country_id;
1346 $result[$key]['country'] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."countries WHERE ID = $country_id");
1347 // $result[$key]['city'] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."countries WHERE ID = $city_id");
1348
1349 $bid_array = get_post_meta( $id, 'current_bid_data', true );
1350
1351 foreach ($bid_array as $dkey => $value) {
1352 $html=get_avatar($bid_array[$dkey]['userid']);
1353 $doc = new DOMDocument();
1354 $doc->loadHTML($html);
1355 $xpath = new DOMXPath($doc);
1356 $src = $xpath->evaluate("string(//img/@src)");
1357 $bid_array[$dkey]['avatar'] = $src;
1358 }
1359
1360 $result[$key]['current_bid_data'] = array_values($bid_array);
1361 $result[$key]['auction_type'] = get_post_meta( $id, 'auction_type', true );
1362 $result[$key]['price_reserve'] = get_post_meta( $id, 'price_reserve', true );
1363 $result[$key]['price_current'] = get_post_meta( $id, 'price_current', true );
1364 $result[$key]['price_shipping'] = get_post_meta( $id, 'price_shipping', true );
1365 $result[$key]['price_bin'] = get_post_meta( $id, 'price_bin', true );
1366 $result[$key]['condition'] = get_post_meta( $id, 'condition', true );
1367
1368 $rating = getRate($id);
1369 $result[$key]['total_rating'] = $rating[0]->total;
1370 if(is_null($rating[0]->total_score)){$rating[0]->total_score = (string)0;}
1371 $result[$key]['total_score'] = $rating[0]->total_score;
1372 if($rating[0]->total_score == 0){
1373 $result[$key]['star_rating'] = (string)0;
1374 }else{
1375 $result[$key]['star_rating'] = (string)($rating[0]->total_score/$rating[0]->total);
1376 }
1377
1378 $result[$key]['topcategory'] = get_post_meta( $id, 'topcategory', true );
1379 $result[$key]['featured'] = get_post_meta( $id, 'featured', true );
1380 $result[$key]['html'] = get_post_meta( $id, 'html', true );
1381 $result[$key]['listing_expiry_date'] = get_post_meta( $id,'listing_expiry_date',true);
1382 $result[$key]['listing_expiry_days'] = get_post_meta( $id,'listing_expiry_days',true);
1383 $result[$key]['hits'] = get_post_meta( $id, 'hits', true );
1384 $result[$key]['bidstring'] = get_post_meta( $id, 'bidstring', true );
1385 $result[$key]['bidwinnerid'] = preg_replace('![^0-9]+!', '', get_post_meta( $id, 'bidwinnerstring', true ));
1386 $userdata = get_userdata(preg_replace('![^0-9]+!', '', get_post_meta( $id, 'bidwinnerstring', true )));
1387 // $userdata = get_userdata(intval(preg_replace('![^0-9]+!','',preg_replace('/\d+/', '', get_post_meta( $id, 'bidwinnerstring', true ),1),1)));
1388 $result[$key]['bidwinnerstring'] = $userdata->user_login;
1389 $result[$key]['image'] = get_post_meta( $id, 'image', true );
1390 $result[$key]['image_array'] = get_post_meta( $id, 'image_array', true);
1391 $result[$key]['video_array'] = get_post_meta( $id, 'video_array', true);
1392 $thumbnailID = get_post_meta( $id, '_thumbnail_id', true );
1393 $thumbnail = wp_get_attachment_image_src($thumbnailID, 'post' );
1394 $result[$key]['thumbnail'] = $thumbnail[0];
1395 return $result;
1396}
1397
1398function getCategories($auctionId){
1399 global $wpdb;
1400 $result = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."term_relationships rel LEFT JOIN ".$wpdb->prefix."term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id WHERE object_id = $auctionId",ARRAY_A);
1401 return $result;
1402}
1403function increaseHits($auctionId){
1404 $hits = get_post_meta( $auctionId, 'hits', true );
1405 $hits = $hits+1;
1406 $result = update_post_meta($auctionId, 'hits',$hits);
1407 return $result;
1408}
1409
1410//Get all auctions
1411///http://mazad-house.com/wp-json/elate-api/v1/getAllAucs/(int) offset value (0-20,20-40,40-60) every page +20 from last
1412function getAllAuctions(WP_REST_Request $request) {
1413 global $wpdb;
1414 $pages = $request['offset'];
1415 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts where post_status = 'publish' and post_type = 'listing_type' LIMIT 15 OFFSET $pages ", ARRAY_A);
1416 foreach ($result as $key => $val) {
1417 $id = $result[$key]['ID'];
1418 $result[$key]['categories']= getCategories($id);
1419 $result = getMetaFormated($id,$result,$key);
1420 }
1421 return array_values($result);
1422}
1423
1424//Get all featured auctions
1425//http://mazad-house.com/wp-json/elate-api/v1/getFeatured/(int) offset value (0-20,20-40,40-60) every page +20 from last
1426function getFeatured(WP_REST_Request $request) {
1427 global $wpdb;
1428 $pages = $request['offset'];
1429 $featured = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."postmeta pm LEFT JOIN ".$wpdb->prefix."posts p ON p.ID = pm.post_id WHERE meta_key='featured'
1430 AND meta_value='yes' AND p.post_status='publish'", ARRAY_A);
1431 foreach ($featured as $key => $value) {
1432 $id = $featured[$key]['ID'];
1433 $featured = getMetaNoFilter($id,$featured,$key);
1434 //if($featured[$key]['listing_expiry_date']=="" && $featured[$key]['bidwinnerstring'] ==""){
1435 if($featured[$key]['listing_expiry_date']=="" || !empty($featured[$key]['bidwinnerstring'])){
1436 unset($featured[$key]);
1437 } else{
1438 unset($featured[$key]['meta_id']);
1439 unset($featured[$key]['post_id']);
1440 unset($featured[$key]['meta_key']);
1441 unset($featured[$key]['meta_value']);
1442 $featured[$key]['categories'] = getCategories($id);
1443
1444 }
1445 $sliced = array_slice($featured, $pages);
1446}
1447return array_values($sliced);
1448}
1449
1450//Get 15 latest auctions
1451function getLatest(WP_REST_Request $request) {
1452 global $wpdb;
1453 $pages = $request['offset'];
1454 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts WHERE post_status = 'publish' and post_type = 'listing_type' ORDER BY ID DESC", ARRAY_A);
1455
1456 foreach ($result as $key => $val) {
1457
1458
1459 $id = $result[$key]['ID'];
1460 $result = getMetaNoFilter($id,$result,$key);
1461
1462 $expiry_date = get_post_meta($id,'listing_expiry_date',true);
1463 //old search
1464 if(($result[$key]['listing_expiry_date']=="" && $result[$key]['bidwinnerstring'] =="") || $expiry_date<current_time('mysql', 1)) {
1465 unset($result[$key]);
1466 } else{
1467 $result[$key]['categories']= getCategories($id);
1468 }
1469 //new search
1470 // if($expiry_date<current_time('mysql', 1)){
1471 // unset($result[$key]);
1472 // } else{
1473 // $i++;
1474 // $result[$key]['categories']= getCategories($id);
1475 // }
1476 // if($i==15) break;
1477}
1478$result=array_slice($result,0,15);
1479return array_values($result);
1480}
1481
1482//Get single auction by ID
1483function getSingleAuction(WP_REST_Request $request) {
1484 global $wpdb;
1485 $auctionId = $request['id'];
1486 $increaseFlag = $request['shouldIncrement'];
1487 if($increaseFlag != 0){
1488 increaseHits($auctionId);
1489 }
1490 $result = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."posts WHERE ID=$auctionId AND post_status = 'publish' AND post_type = 'listing_type'",ARRAY_A);
1491 foreach ($result as $key => $val) {
1492 $result[$key]['categories']=getCategories($auctionId);
1493 $result = getMetaNoFilter($auctionId,$result,$key);
1494 }
1495 return $result;
1496}
1497
1498//Get all categories
1499//http://mazad-house.com/wp-json/elate-api/v1/getAllTerms
1500function getAllTerms(WP_REST_Request $request) {
1501 global $wpdb, $GLOBALS;
1502 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."term_taxonomy tax LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id", ARRAY_A);
1503 foreach ($result as $key => $value) {
1504 $result[$key]['img'] = $GLOBALS['CORE_THEME']['category_icon_'.$result[$key]['term_id']];
1505 }
1506return $result;
1507}
1508
1509//Add auction to favorite list
1510//http://mazad-house.com/wp-json/elate-api/v1/addToFavoritesList/(int)userID/(int)auctionId
1511function addToFavoritesList(WP_REST_Request $request){
1512 if(verifyToken($request['uid'])){
1513 $favlist=get_user_meta($request['uid'],'favorite_list', true);
1514 //$favlist[count($favlist)]=$request['auctionid'];
1515
1516 if(is_array($favlist)){
1517 if(array_search($request['auctionid'],$favlist))
1518 {
1519 return false;
1520
1521 }
1522 else {
1523 array_push($favlist,$request['auctionid']);
1524 }
1525 }
1526 else {
1527 $favlist = array($request['auctionid']);
1528 }
1529
1530
1531 $result=update_user_meta($request['uid'], 'favorite_list', $favlist);
1532
1533 if(!empty($result) && $result!=false){
1534 $result = true;
1535 }else{
1536 $result = false;
1537 }
1538return $result;
1539}
1540else {
1541 return 'Access error!';
1542}
1543}
1544
1545function deleteFromFavorites (WP_REST_Request $request){
1546 if(verifyToken($request['uid'])){
1547 $favlist=get_user_meta($request['uid'],'favorite_list', true);
1548 $key = array_search($request['auctionid'],$favlist);
1549 unset($favlist[$key]);
1550 $result=update_user_meta($request['uid'], 'favorite_list', $favlist);
1551 if(!empty($result) && $result!=false){
1552 $result = true;
1553 }else{
1554 $result = false;
1555 }
1556 return $result;
1557 }
1558 else {
1559 return 'Access error!';
1560 }
1561}
1562
1563//Get EndingSoon Auctions (time < 60 min) and slice array on pages
1564function getEndingAuctions (WP_REST_Request $request) {
1565 global $wpdb;
1566 $pages = $request['offset'];
1567 $all_auctions = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."posts where post_status = 'publish' and post_type = 'listing_type' ", ARRAY_A);
1568 for($key=0;$key<count($all_auctions);$key++){
1569
1570 $id = $all_auctions[$key]['ID'];
1571 $expiry_date = get_post_meta($id,'listing_expiry_date',true);
1572
1573 if(!empty($expiry_date) && $expiry_date!=""){
1574 $now = new DateTime();
1575 $d1 = new DateTime($expiry_date);
1576 $interval = date_diff($d1, $now);
1577 $hours = $interval->h;
1578 $hours = $hours + ($interval->days*24);
1579 $minutes = $hours * 60;
1580 if($minutes<=60){
1581 $expired[$key]=$all_auctions[$key];
1582 // $categories = $wpdb->get_results("SELECT * FROM wp_term_relationships rel LEFT JOIN wp_term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id LEFT JOIN wp_terms te ON tax.term_id=te.term_id WHERE object_id = $auctionId",ARRAY_A);
1583 $expired[$key]['categories']=getCategories($id);
1584 $expired = getMetaFormated($id,$expired,$key);
1585 }
1586 }
1587}
1588$sliced = array_slice($expired, $pages);
1589return $sliced;
1590}
1591
1592//setBid on auction
1593function setBid (WP_REST_Request $request) {
1594 global $CORE, $wpdb;
1595 $parameters = $request->get_params();
1596
1597 $postId = $parameters['auctionid'];
1598 $userId = $parameters['userid'];
1599 $userName = $parameters['username'];
1600// if(verifyToken($userId)){
1601 if(isset($parameters['auction_action'])){
1602 $title = $wpdb->get_results("SELECT post_title FROM ".$wpdb->prefix."posts where ID=$postId and post_status = 'publish'", ARRAY_A);
1603 $post_title = $title[0]['post_title'];
1604 $expiry_date = get_post_meta($postId,'listing_expiry_date',true);
1605 if($expiry_date == "" || ( strtotime($expiry_date) < strtotime(current_time( 'mysql' )))){
1606 return $GLOBALS['error_message'] = "Auction Finished";
1607 }
1608
1609 switch($parameters['auction_action']){
1610 case "buynow": {
1611 return "BUYNOW!!!";
1612 break;
1613 }
1614 case "newbid": {
1615 if(!is_numeric($parameters['price'])){
1616 $GLOBALS['error_message'] = str_replace("%a", $parameters['price'] ,"Bid amount of (%a) is invalid.");
1617 }else{
1618
1619 $current_bidding_data = get_post_meta($postId,'current_bid_data',true);
1620 if(!is_array($current_bidding_data)){ $current_bidding_data = array(); }
1621
1622 //2. ORDER IT BY KEY (WHICH HOLDS THE BID AMOUNT)
1623 krsort($current_bidding_data);
1624
1625 // GET THE CURRENT PRICE
1626 $current_price = get_post_meta($postId,'price_current',true);
1627 if($current_price == ""){ $current_price = 0; }
1628
1629 if( $parameters['price'] > $current_price ){
1630 // LETS CHECK IF WE HAVE A BIGGER AMOUNT THAN THE BIDDERS TOTAL
1631 $checkme = current($current_bidding_data);
1632 //if($checkme['max_amount'])
1633 // OLD BIDDER IS STILL WINNER
1634 if(is_numeric($current_price) && $current_price > 0 && isset($checkme['max_amount']) && ( $checkme['max_amount'] >= $parameters['price']) ){
1635
1636 $is_new_bid = false;
1637
1638 if($parameters['price'] == $checkme['max_amount'] ){
1639 $current_price = $checkme['max_amount'];
1640 }
1641 elseif( $parameters['price']+1 > $checkme['max_amount'] ){
1642 $current_price = $checkme['max_amount'];
1643 }
1644 elseif( $parameters['price']+1 > $checkme['max_amount'] ){
1645
1646 $current_price = $parameters['price']+0;
1647
1648 }else{
1649
1650 $current_price = $parameters['price']+0;
1651 }
1652
1653 $GLOBALS['error_message'] = "You have been outbid!";
1654 }else{
1655 $is_new_bid = true;
1656 // EMAIL THE OLD BIDDER AND LET THEM KNOW THEY HAVE BEEN OUTBID
1657 if(isset($checkme['userid'])){
1658 $_POST['username'] = $checkme['username'];
1659
1660 $_POST['title'] = $post_title;
1661 $_POST['link'] = get_permalink($postId);
1662 $CORE->SENDEMAIL($checkme['userid'],'auction_outbid');
1663 }
1664 // NOW SET NEW PRICE
1665 if($current_price == "" || $current_price == "0"){
1666
1667 $current_price = 1;
1668
1669 // SAME USER UPDATING THEIR MAX BID
1670 }elseif(isset($checkme['userid'])){
1671
1672 $current_price = $parameters['price']+0;
1673
1674 // BID IT HIGHER THAN OLD MAX BID
1675 }elseif(isset($checkme['max_amount']) && $parameters['price'] > $checkme['max_amount'] ){
1676
1677 $current_price = $parameters['price']+0;
1678
1679 // BID +1
1680 }elseif( ($current_price + 1) <= $parameters['price'] ){
1681
1682 $current_price = $parameters['price']+0;
1683
1684 // NEW BID + 0.1
1685 }else{
1686
1687 $current_price = $parameters['price']+0;
1688
1689 }
1690 $GLOBALS['error_message'] = "You are now the highest bidder";
1691
1692 }
1693
1694 }else{
1695 // LEAVE MSG
1696 $GLOBALS['error_message'] = str_replace("%a", $parameters['price'] ,"Bid amount of (%a) is invalid.");
1697 }
1698 update_post_meta($postId,'price_current', $current_price);
1699
1700}
1701break;
1702 } //END CASE
1703 } //END SWITCH
1704 }//END IF
1705
1706 if($is_new_bid){
1707 $current_bidding_data[$parameters['price']] = array( 'max_amount' => $parameters['price'],
1708 'userid' => $userId, 'username' => $userName,
1709 'date' => current_time( 'mysql' ), 'bid_type' => 'bid' );
1710
1711 $last_user=get_post_meta($postId,'bidstring', true);
1712 preg_match('/(.*)(-[0-9].*-)/',$last_user,$matches);
1713 $last_user_id=str_replace("-","",$matches[2]);
1714 if($last_user_id!==$userId){
1715 $lang_user=get_user_meta($last_user_id,'language',true);
1716 $lang_seller=get_user_meta(get_post_field('post_author', $postId),'language',true);
1717 if($lang_user=="EN"){
1718 $notification_body = GetNotificationMessageForAuction($postId, "test", "Your bid is no longer the highest in auction",
1719 "test", "Auction Outbid", "Auction name (EN)") ;
1720 }
1721 else {
1722 $notification_body = GetNotificationMessageForAuction($postId, NULL,
1723 "لم تعد ØµØ§ØØ¨ أعلى مزايدة ÙÙŠ المزاد رقم",
1724 NULL, "مزايدة جديدة", "Auction name (AR)") ;
1725 }
1726 $notification_title = '';
1727 $notification_user_id = $last_user_id;
1728
1729 sendPushP($notification_user_id, $notification_title, $notification_body);
1730 }
1731 //4. MERGE THE TWO AND SAVE
1732 $result = update_post_meta($postId,'current_bid_data', $current_bidding_data);
1733 // SET FLAG SO SYSTEM KNOWS WHO THE CURRENT WINNING BIGGER IS
1734 update_post_meta($postId,'bidstring', get_post_meta($postId,'bidstring', true)."-".$userId."-");
1735
1736
1737 $last_user=get_post_meta($postId,'bidstring', true);
1738 preg_match('/(.*)(-[0-9].*-)/',$last_user,$matches);
1739 $last_user_id=str_replace("-","",$matches[2]);
1740// SendPush for out bid user
1741
1742// //SendPush for seller
1743 if($lang_seller=="EN"){
1744 $notification_body_seller = GetNotificationMessageForAuction($postId, NULL, "You received new bid on auction",
1745 NULL, "Bid Received", "Auction name (EN)") ;
1746 }
1747 else {
1748 $notification_body_seller = GetNotificationMessageForAuction($postId, NULL,
1749 "لقد تلقيت مزايدة جديدة ÙÙŠ المزاد رقم",
1750 NULL, "مزايدة جديدة", "Auction name (EN)") ;
1751 }
1752
1753 $notification_title_seller = '';
1754 $notification_user_id_seller = get_post_field('post_author', $postId);
1755 sendPushP($notification_user_id_seller, $notification_title_seller, $notification_body_seller);
1756
1757 }
1758 update_option('wlt_system_counts','');
1759 $user_bidding_data = get_user_meta($userId,'user_bidding_data',true);
1760 if(!is_array($user_bidding_data)){ $user_bidding_data = array(); }
1761 $user_bidding_data[] = array('postid' => $postId,
1762 'max_amount' =>$parameters['price'],
1763 'date' => current_time( 'mysql' ),
1764 'bid_type' => 'bid',
1765 'title' => $post_title);
1766 update_user_meta($userId,'user_bidding_data',$user_bidding_data);
1767
1768 if(is_null($result)){
1769 $result = array('status' => 'error', 'message' => 'Your price is lower than current');
1770 return $result;
1771 }
1772
1773 return $current_bidding_data;
1774
1775//}
1776//else {
1777// return 'Access Error';
1778//}
1779}
1780
1781function buyNow(WP_REST_Request $request){
1782 global $CORE;
1783 // SET THE CURRENT PRICE TO THE BUYNOW PRICE
1784 $parameters = $request->get_params();
1785
1786 $postId = $parameters['auctionid'];
1787 $userId = $parameters['userid'];
1788 if(verifyToken($userId)){
1789 $userName = $parameters['username'];
1790 $post = get_post($postId);
1791
1792 $bin_price = get_post_meta($postId,'price_bin',true);
1793 update_post_meta($postId,'price_current', $bin_price);
1794
1795 //3. ADD ON THE NEW BID
1796 $current_bidding_data[$bin_price] = array( 'max_amount' => $bin_price,
1797 'userid' => $userId,
1798 'username' => $userName,
1799 'date' => current_time('mysql'),
1800 'bid_type' => "buynow" );
1801
1802 //4. UPDATE USER META TO INDICATE THEY BID ON THIS ITEM
1803 $user_bidding_data = get_user_meta($userId,'user_bidding_data',true);
1804 if(!is_array($user_bidding_data)){ $user_bidding_data = array(); }
1805 $user_bidding_data[] = array('postid' => $postId, 'max_amount' => $bin_price, 'date' => current_time( 'mysql' ), 'bid_type' => 'bin', 'title' => $post->post_title);
1806 update_user_meta($userId,'user_bidding_data',$user_bidding_data);
1807 //4. MERGE THE TWO AND SAVE
1808 update_post_meta($post->ID,'current_bid_data', $current_bidding_data);
1809
1810 //5. SEND EMAIL TO BIDDERS
1811 $_POST['winningbid'] = hook_price($bin_price);
1812 $_POST['title'] = $post->post_title;
1813 $_POST['link'] = get_permalink($post->ID);
1814
1815 // SEND EMAIL
1816 $_POST['username'] = $userName;
1817
1818 $CORE->SENDEMAIL($userId,'auction_ended_winner');
1819 // LOOP BIDDERS
1820
1821 krsort($current_bidding_data); // order data
1822
1823 if(is_array($current_bidding_data) && !empty($current_bidding_data)){
1824 $sent_to_array = array();
1825 // SEND EMAIL
1826 $_POST['username'] = $userName;
1827 $CORE->SENDEMAIL($userId,'auction_ended_winner');
1828
1829
1830 foreach($current_bidding_data as $maxbid=>$data){
1831
1832 if($i == 1 && $data['max_amount'] > 0 ){
1833 }else{
1834 if(!in_array($data['userid'],$sent_to_array)){
1835 $_POST['username'] = $data['username'];
1836 $CORE->SENDEMAIL($data['userid'],'auction_ended');
1837 array_push($sent_to_array,$data['userid']);
1838 } // end if
1839 }// end else
1840 $i++;
1841 }
1842 }
1843 //6. SEND EMAIL TO AUCTION SELLER
1844
1845 $author_data = get_userdata( $post->post_author );
1846
1847 $_POST['username'] = $author_data->display_name;
1848 $CORE->SENDEMAIL($post->post_author,'auction_ended_owner');
1849
1850 // 7. IF THE ITEM SOLD, ADD A COMISSION AMOUNT TO THE USERS ACCOUNT SO THEY HAVE TO PAY THE ADMIN
1851 $comissionadded = 0;
1852 $price_current = get_post_meta($post->ID,'price_current',true);
1853 if($price_current > 0 && isset($GLOBALS['CORE_THEME']['auction_house_percentage']) && strlen($GLOBALS['CORE_THEME']['auction_house_percentage']) > 0){
1854
1855 // WORK OUT AMOUNT OWED BY THE SELLER
1856 $AMOUNTOWED = ($GLOBALS['CORE_THEME']['auction_house_percentage']/100)*$price_current;
1857 $AMOUNTOWED = -1 * abs($AMOUNTOWED);
1858
1859 // DEDUCT AMOUNT FROM MEMBERS AREA
1860 $user_balance = get_user_meta($post->post_author,'wlt_usercredit',true);
1861 if($user_balance == ""){ $user_balance = 0; }
1862 $user_balance = $user_balance+$AMOUNTOWED;
1863 update_user_meta($post->post_author,'wlt_usercredit',$user_balance);
1864
1865 $comissionadded = $AMOUNTOWED;
1866
1867 }
1868
1869 // CHECK FOR QTY ADDED IN 8.2
1870 $qty = get_post_meta($post->ID,'qty',true);
1871
1872 if(is_numeric($qty) && $qty > 0){
1873 $qty_sold = get_post_meta($post->ID,'qty_sold',true);
1874 if(!is_numeric($qty_sold)){ $qty_sold = 1; }else{ $qty_sold = $qty_sold + 1; }
1875 update_post_meta($post->ID,'qty_sold',$qty_sold);
1876
1877 // IF SOLD MORE THAN QTY EXPIRE LISTING
1878 if($qty_sold > $qty){
1879 update_post_meta($post->ID,'listing_expiry_date','');
1880 }
1881 // SET FLAG SO SYSTEM KNOWS WHO THE CURRENT WINNING BIGGER IS
1882 update_post_meta($post->ID,'bidstring', '');
1883 update_post_meta($post->ID,'bidwinnerstring', get_post_meta($post->ID,'bidwinnerstring', true)."-".$userId."-");
1884 }else{
1885 // REMOVE EXPIRY FOR AUTO EXPIRY SO THE CORE SYSTEM DOESNT PICK IT UP
1886 // AND THE LISTING IS THEN FINISHED
1887 update_post_meta($post->ID,'listing_expiry_date','');
1888 update_post_meta($post->ID,'bidstring', '');
1889 update_post_meta($post->ID,'bidwinnerstring', get_post_meta($post->ID,'bidwinnerstring', true)."-".$userId."-");
1890 }
1891 // LEAVE MSG
1892 $GLOBALS['error_message'] = $CORE->_e(array('auction','28'))."<style>.timeleftbox { display:none; }</style>";
1893
1894 // ADD LOG ENTRY
1895 $CORE->ADDLOG("<a href='(plink)'>".$post->post_title.'</a> auction finished. (buy now / comission '.$comissionadded.')', $post->ID,'','label-inverse');
1896
1897 // SEND EMAIL TO THE SELLER
1898 $CORE->SENDEMAIL($post->post_author,'auction_itemsold');
1899
1900 // RESET COUNTERS
1901 update_option('wlt_system_counts','');
1902 return array_values($current_bidding_data);
1903 }
1904 else {
1905 return 'Access error!';
1906 }
1907 }
1908
1909function password_retrieve(WP_REST_Request $request){
1910 global $wpdb, $wp_hasher;
1911 $user_login = $request["username"];
1912 if ( empty( $user_login) ) {
1913 return false;
1914 } else if ( strpos( $user_login, '@' ) ) {
1915 $user_data = get_user_by( 'email', trim( $user_login ) );
1916 if ( empty( $user_data ) )
1917 return false;
1918} else {
1919 $login = trim($user_login);
1920 $user_data = get_user_by('login', $login);
1921}
1922if(verifyToken($user_data->id)){
1923
1924 do_action('lostpassword_post');
1925 if ( !$user_data ) return false;
1926 // redefining user_login ensures we return the right case in the email
1927 $user_login = $user_data->user_login;
1928 $user_email = $user_data->user_email;
1929// do_action('retreive_password', $user_login); // Misspelled and deprecated
1930 do_action('retrieve_password', $user_login);
1931 $allow = apply_filters('allow_password_reset', true, $user_data->ID);
1932 if ( ! $allow )
1933 return false;
1934 else if ( is_wp_error($allow) )
1935 return false;
1936 $key = wp_generate_password( 20, false );
1937 do_action( 'retrieve_password_key', $user_login, $key );
1938
1939 if ( empty( $wp_hasher ) ) {
1940 require_once ABSPATH . 'wp-includes/class-phpass.php';
1941 $wp_hasher = new PasswordHash( 8, true );
1942 }
1943 $hashed = $wp_hasher->HashPassword( $key );
1944 $wpdb->update( $wpdb->users, array( 'user_activation_key' => time().":".$hashed ), array( 'user_login' => $user_login ) );
1945 $message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
1946 $message .= network_home_url( '/' ) . "\r\n\r\n";
1947 $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
1948 $message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
1949 $message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
1950 $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . ">\r\n";
1951
1952 if ( is_multisite() )
1953 $blogname = $GLOBALS['current_site']->site_name;
1954 else
1955 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1956
1957 $title = sprintf( __('[%s] Password Reset'), $blogname );
1958
1959 $title = apply_filters('retrieve_password_title', $title);
1960 $message = apply_filters('retrieve_password_message', $message, $key);
1961
1962 if ( $message && !wp_mail($user_email, $title, $message) )
1963 wp_die( __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') );
1964
1965 $result = array('user_email' => $user_email,
1966 'user_login' => $user_login,
1967 'message' => 'Link has been sent to email',
1968 'status' => 'success');
1969
1970 return $result;
1971 }
1972 else {
1973 return "Access error!";
1974 }
1975}
1976
1977function signup (WP_REST_Request $request){
1978 global $wpdb, $table_prefix;
1979
1980 $table_name = $table_prefix . 'smsregister';
1981 $table_errors_name = $table_prefix . 'smsregister_errors';
1982 $user_name = $request["username"];
1983 $phone_number = $request["phonenumber"];
1984 $email = $request["email"];
1985 $locale = $request["locale"];
1986
1987
1988 if($email){
1989
1990 $phones = $wpdb->get_results("SELECT meta_value FROM wp_usermeta WHERE meta_key='phone'");
1991
1992 foreach ($phones as $value) {
1993
1994 if($value->meta_value == $phone_number){
1995 $result = array( 'status' => 'error', 'message' => 'This phone is already registered');
1996 return $result;
1997 }
1998 }
1999
2000 $user = get_user_by('email',$email);
2001 if($user){
2002 $result = array( 'status' => 'error', 'message' => 'This email is already registered. Please enter a new email');
2003 return $result;
2004 }else{
2005 if($user_name){
2006 $user = get_user_by('login',$user_name);
2007 if($user)
2008 {
2009 $result = array( 'status' => 'error', 'message' => 'Username already exists, please choose another');
2010 return $result;
2011 }else{
2012 if ($phone_number) {
2013 $data = $wpdb->get_row("SELECT * FROM $table_name
2014 WHERE phone_number='".addslashes($phone_number)."' AND status=1",ARRAY_A);
2015
2016 if (!$data) {
2017 $code = mt_rand(1000, 9999);
2018 if($locale == "arabic"){
2019 $msg = sprintf('استخدم الرمز %s لاكمال التسجيل ÙÙŠ كيّش', $code);
2020 }else{
2021 $msg = sprintf('Use the code %s to complete your registration at Kayish', $code);
2022 }
2023 $url = 'http://api.unifonic.com/rest/Messages/Send';
2024
2025 $params = array (
2026 'Recipient' => $phone_number,
2027 'Body' => $msg,
2028 'AppSid' => 'mLPnnX8zWRUlFIVCXFH5wOszKHBGfk',
2029 'encoding' => 'encoding=UTF8',
2030 'SenderID' => 'Kayish',
2031 );
2032
2033 $postString = http_build_query($params, '', '&');
2034
2035 $additional_headers = array(
2036 'userid: Basic bWhvdXNlIDpNaG91c2VfMTE=',
2037 'Content-Type: application/x-www-form-urlencoded'
2038 );
2039
2040 $ch = curl_init($url);
2041 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
2042 curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
2043 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2044 //curl_setopt($ch, CURLOPT_HTTPHEADER, $additional_headers);
2045
2046 $server_output = curl_exec ($ch);
2047 $resp = json_decode($server_output,true);
2048 if ($resp['success'] == true) {
2049 $wpdb->query("INSERT INTO ".$table_name." (username, phone_number, sent_code, sent_sms, last_sent, status)
2050 VALUES ('".addslashes($user_name)."', '".$phone_number."', ".$code.", 1, '".time(TRUE)."', 0);");
2051 return $server_output;
2052 } else {
2053 $result = array( 'status' => 'error', 'message' => 'error');
2054 return $result;
2055 }
2056
2057 } else {
2058 $result = array( 'status' => 'error', 'message' => 'This phone number is already registered. Please enter a new phone number');
2059 return $result;
2060 }
2061 }
2062 else {
2063 $result = array( 'status' => 'error', 'message' => 'Phonenumber not found');
2064 return $result;
2065 }
2066}
2067}
2068}
2069}
2070}
2071
2072function validateCode (WP_REST_Request $request) {
2073 global $wpdb;
2074 $password = $request["password"];
2075 $email = $request["email"];
2076 $phone_number = $request["phonenumber"];
2077 $code = $request["code"];
2078
2079 if ($phone_number and $code) {
2080 $info = $wpdb->get_results("SELECT * FROM wp_smsregister WHERE phone_number= $phone_number and sent_code=$code and status=0",ARRAY_A);
2081 if($info){
2082 $result = $wpdb->query("UPDATE wp_smsregister SET status=1 WHERE phone_number= $phone_number and sent_code=$code");
2083 if($result==1){
2084 $user_id = wp_create_user($info[0]['username'], $password, $email);
2085 $result = update_user_meta($user_id, 'phone', $phone_number);
2086 $rt = new WP_REST_Request('GET','/elate-api/v1/userInfo/'.$user_id.'');
2087 $rsp = rest_do_request($rt);
2088 return $rsp;
2089 }else{
2090 $result = array( 'status' => 'error', 'message' => 'Registration error');
2091 return $result;
2092 }
2093 }else{
2094 $result = array( 'status' => 'error', 'message' => 'Incorrect Verification code, please try again');
2095 return $result;
2096 }
2097}else{
2098 $result = array( 'status' => 'error', 'message' => 'No data found');
2099 return $result;
2100}
2101}
2102
2103
2104
2105function getUserInfo(WP_REST_Request $request) {
2106 global $wpdb;
2107 $userid = $request['uid'];
2108
2109 $userarray = get_userdata($userid);
2110
2111 $userinfo['ID'] = $userarray->data->ID;
2112 $userinfo['user_login'] = $userarray->data->user_login;
2113 $userinfo['display_name'] = $userarray->data->display_name;
2114 $userinfo['user_email'] = $userarray->data->user_email;
2115 $userinfo['user_registered'] = $userarray->data->user_registered;
2116 $userinfo['phone']= get_user_meta($userid, 'phone', true);
2117 $userinfo['first_name'] = get_user_meta($userid, 'first_name', true);
2118 $userinfo['last_name'] = get_user_meta($userid, 'last_name', true);
2119 $userinfo['skype'] = get_user_meta($userid, 'skype', true);
2120 $userinfo['facebook'] = get_user_meta($userid, 'facebook', true);
2121 $userinfo['linkedin'] = get_user_meta($userid, 'linkedin', true);
2122 $userinfo['twitter'] = get_user_meta($userid, 'twitter', true);
2123 $ISO_COUNTRY = get_user_meta($userid, 'country', true);
2124 if(!empty($ISO_COUNTRY)){
2125 $userinfo['country'] = getCountryFull($ISO_COUNTRY);
2126 }else{
2127 $userinfo['country'] = null;
2128 }
2129 $userinfo['description'] = get_user_meta($userid, 'description', true);
2130 $html=get_avatar($userid);
2131 $doc = new DOMDocument();
2132 $doc->loadHTML($html);
2133 $xpath = new DOMXPath($doc);
2134 $src = $xpath->evaluate("string(//img/@src)");
2135 $userinfo['avatar'] = $src;
2136 $userinfo['roles'] = $userarray->roles;
2137
2138 $rating = getRateByUserId($userid);
2139 $userinfo['total_rating'] = $rating[0]->total;
2140
2141 if(is_null($rating[0]->total_score)){
2142 $rating[0]->total_score = (string)0;
2143 }
2144 $userinfo['total_score'] = $rating[0]->total_score;
2145 if($rating[0]->total_score == 0){
2146 $userinfo['star_rating'] = (string)0;
2147 }else{
2148 $userinfo['star_rating'] = (string)($rating[0]->total_score/$rating[0]->total);
2149 }
2150 $count_created = $wpdb->get_row("SELECT COUNT(*) as total FROM ".$wpdb->prefix."posts WHERE post_author=".$userid." AND post_type = 'listing_type' AND post_status = 'publish'");
2151 $userinfo['auctions_create_count'] = $count_created->total;
2152
2153
2154 $SQL = "SELECT count(*) AS total_wins FROM ".$wpdb->prefix."posts
2155 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
2156 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
2157 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
2158 AND mt2.meta_key = 'bidwinnerstring' AND mt2.meta_value LIKE ('%-".$userid."-%')";
2159 $total_wins = $wpdb->get_row($SQL);
2160
2161 $userinfo['auctions_won_count'] = $total_wins->total_wins;
2162
2163 $count_sold = $wpdb->get_row("SELECT COUNT(*) as total FROM ".$wpdb->prefix."postmeta as meta INNER JOIN ".$wpdb->prefix."posts p ON p.ID=meta.post_id WHERE meta_key='bidwinnerstring' and p.post_author=".$userid." and meta_value <> ''");
2164 $userinfo['auctions_sold_count'] = $count_sold->total;
2165
2166 $count_feedbacks = $wpdb->get_row("SELECT COUNT(*) as total FROM wp_postmeta m INNER JOIN wp_posts p on p.ID = m.post_id WHERE meta_key='uid' and meta_value=".$userid."");
2167 $userinfo['feedback_count'] = $count_feedbacks->total;
2168
2169
2170 return $userinfo;
2171}
2172
2173function getFavorites(WP_REST_Request $request){
2174 global $wpdb;
2175 $userid = $request['uid'];
2176 if(verifyToken($userid)){
2177 $favlist = get_user_meta($userid,'favorite_list', true);
2178 if(is_null($favlist) || empty($favlist)){
2179 $favlist = array();
2180 return $favlist;
2181 }else{
2182 foreach ($favlist as $key => $value) {
2183
2184 $auctionId = $favlist[$key];
2185 $post[$key] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."posts WHERE ID=$auctionId AND post_type = 'listing_type' and post_status = 'publish'", ARRAY_A);
2186 if($post[$key]!= null){
2187 $post[$key]['categories'] = getCategories($auctionId);
2188 $post = getMetaNoFilter($auctionId,$post,$key);
2189 }else{
2190 unset($post[$key]);
2191 }
2192
2193 }
2194 }
2195 if(is_null($post) || empty($post)){
2196 $post = array();
2197 return $post;
2198 }else{
2199 return array_values($post);
2200 }
2201 }
2202 else {
2203 return "Access error!";
2204 }
2205}
2206
2207function deleteAuction(WP_REST_Request $request){
2208 global $wpdb;
2209 $auctionId = $request['auctionid'];
2210 $userId = $request['userid'];
2211 if(verifyToken($userId)){
2212 $result = $wpdb->get_results( "SELECT post_author FROM `wp_posts` WHERE ID=$auctionId AND post_type = 'listing_type'", ARRAY_A);
2213 $bidstring = get_post_meta( $auctionId, 'bidstring', true );
2214 $bidwinnerstring = get_post_meta( $auctionId, 'bidwinnerstring', true );
2215
2216 if($result[0]['post_author'] == $userId && empty($bidstring) && empty($bidwinnerstring)){
2217 $result = wp_trash_post($auctionId);
2218 return $result;
2219 }else{
2220 $result = array( 'status' => 'error', 'message' => 'Delete error');
2221 return $result;
2222 }
2223}
2224else {
2225 return "Access error!";
2226}
2227}
2228
2229
2230
2231function auctionsBySubcategory(WP_REST_Request $request){
2232
2233 global $wpdb;
2234 $id = $request['categoryid'];
2235 $pages = $request['offset'];
2236 $result_array = array();
2237
2238 $auctions = $wpdb->get_results("SELECT DISTINCT object_id FROM ".$wpdb->prefix."term_relationships rel LEFT JOIN ".$wpdb->prefix."term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id
2239 LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id WHERE tax.parent =$id ", ARRAY_A);
2240
2241
2242
2243 if(empty($auctions)){
2244 $auctions = $wpdb->get_results("SELECT DISTINCT object_id FROM ".$wpdb->prefix."term_relationships rel LEFT JOIN ".$wpdb->prefix."term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id
2245 LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id WHERE rel.term_taxonomy_id =$id", ARRAY_A);
2246 }
2247
2248
2249
2250//foreach ($auctions as $key ) {
2251 foreach ($auctions as $key => $value) {
2252 $id = $auctions[$key]['object_id'];
2253 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts WHERE ID=".$id." AND post_type = 'listing_type'and post_status = 'publish' LIMIT 15 OFFSET $pages ",ARRAY_A);
2254
2255
2256 foreach ($result as $key => $val) {
2257
2258 $result[$key]['categories']=getCategories($id);
2259
2260 $result = getMetaFormated($id,$result,$key);
2261
2262 array_push($result_array, $result[0]);
2263
2264 }
2265
2266 }
2267
2268
2269
2270 foreach($result_array as $key => $val)
2271 {
2272 if($val==null) {
2273 unset($result_array[$key]);
2274 }
2275
2276
2277 }
2278
2279
2280
2281 $filtered_result = array_filter($result_array);
2282
2283 usort($filtered_result, function($a, $b){ return strcmp ($a['bidwinnerstring'], $b['bidwinnerstring']); });
2284 // usort($filtered_result, function($a, $b){return -($a[0]['bidwinnerstring'] - $b[0]['bidwinnerstring']); });
2285 usort($filtered_result, function($a, $b){return strcmp ($b['topcategory'], $a['topcategory'] ); });
2286
2287
2288
2289 return array_values($filtered_result);
2290}
2291
2292function auctionsByName(WP_REST_Request $request){
2293 global $wpdb;
2294 $name = $request['name'];
2295 $pages = $request['offset'];
2296
2297 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts where post_title LIKE '%$name%' and post_type='listing_type' and post_status = 'publish' LIMIT 15 OFFSET $pages ", ARRAY_A);
2298 $nextoffset = count($result);
2299 foreach ($result as $key => $val) {
2300 $id = $result[$key]['ID'];
2301 $result[$key]['nexoffset']=$nexoffset;
2302 $result[$key]['categories']=getCategories($id);
2303 $result = getMetaFormated($id,$result,$key);
2304 }
2305 return array_values($result);
2306}
2307
2308function searchFilter(WP_REST_Request $request){
2309 global $wpdb;
2310 $text = $request["text"];
2311 $catId = $request["catId"];
2312 $priceMin = $request["priceMin"];
2313 $priceMax = $request["priceMax"];
2314 $sort = $request["sort"];
2315 $offset = $request["offset"];
2316 //$city = $request["city"];
2317 //$condition = $request["condition"];
2318 if($sort){
2319 if($sort=0){
2320 $orderby = "ORDER BY object_id DESC";
2321 }
2322 if($sort=1){
2323 $orderby = "ORDER BY post_date DESC";
2324 }
2325 if($sort=1){
2326 $orderby = "ORDER BY post_title ASC";
2327 }
2328 }
2329
2330 if($text and $catId != 0 AND $priceMax!=0){
2331 $categories = $wpdb->get_results("SELECT DISTINCT object_id FROM ".$wpdb->prefix."term_relationships rel LEFT JOIN ".$wpdb->prefix."term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id LEFT JOIN ".$wpdb->prefix."posts p ON rel.object_id = p.ID LEFT JOIN ".$wpdb->prefix."postmeta m ON p.ID= m.post_id WHERE p.post_status='publish' AND te.term_id = $catId OR tax.parent=$catId AND p.post_type='listing_type' AND p.post_title like '%$text%' AND m.meta_key = 'price_current' AND m.meta_value BETWEEN $priceMin AND $priceMax ".$orderby." LIMIT 15 OFFSET $offset",ARRAY_A);
2332 }
2333
2334 if($text and $catId != 0 AND $priceMax==0){
2335 $categories = $wpdb->get_results("SELECT DISTINCT object_id FROM ".$wpdb->prefix."term_relationships rel LEFT JOIN ".$wpdb->prefix."term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id LEFT JOIN ".$wpdb->prefix."posts p ON rel.object_id = p.ID LEFT JOIN ".$wpdb->prefix."postmeta m ON p.ID= m.post_id WHERE p.post_status='publish' AND te.term_id = $catId OR tax.parent=$catId AND p.post_type='listing_type' AND p.post_title like '%$text%' AND m.meta_key = 'price_current' AND m.meta_value >= $priceMin ".$orderby." LIMIT 15 OFFSET $offset",ARRAY_A);
2336 }
2337
2338 if($text and $catId == 0 AND $priceMax != 0){
2339 $categories = $wpdb->get_results("SELECT DISTINCT object_id FROM ".$wpdb->prefix."term_relationships rel LEFT JOIN ".$wpdb->prefix."term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id LEFT JOIN ".$wpdb->prefix."posts p ON rel.object_id = p.ID LEFT JOIN ".$wpdb->prefix."postmeta m ON p.ID= m.post_id WHERE p.post_status='publish' AND p.post_type='listing_type' AND p.post_title like '%$text%' AND m.meta_key = 'price_current' AND m.meta_value BETWEEN $priceMin AND $priceMax ".$orderby." LIMIT 15 OFFSET $offset",ARRAY_A);
2340 }
2341
2342 if($text and $catId == 0 AND $priceMax == 0){
2343 $categories = $wpdb->get_results("SELECT DISTINCT object_id FROM ".$wpdb->prefix."term_relationships rel LEFT JOIN ".$wpdb->prefix."term_taxonomy tax ON rel.term_taxonomy_id = tax.term_taxonomy_id LEFT JOIN ".$wpdb->prefix."terms te ON tax.term_id=te.term_id LEFT JOIN ".$wpdb->prefix."posts p ON rel.object_id = p.ID LEFT JOIN ".$wpdb->prefix."postmeta m ON p.ID= m.post_id WHERE p.post_status='publish' AND p.post_type='listing_type' AND p.post_title like '%$text%' AND m.meta_key = 'price_current' AND m.meta_value >= $priceMin ".$orderby." LIMIT 15 OFFSET $offset",ARRAY_A);
2344 }
2345
2346
2347 if(empty($categories)){
2348 $result = array();
2349 return $result;
2350 }
2351 else{
2352 for($key=0;$key<count($categories);$key++){
2353 $id = $categories[$key]['object_id'];
2354
2355 $result[$key] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."posts where post_type = 'listing_type' and post_status = 'publish' and ID=$id",ARRAY_A);
2356 $result[$key]['categories'] = getCategories($id);
2357 $result = getMetaNoFilter($id,$result,$key);
2358 }
2359
2360 }
2361 return $result;
2362}
2363
2364
2365function addNewAuction(WP_REST_Request $request){
2366
2367 global $CORE, $wpdb;
2368 //$_POST['enhancement_3'] - HTML
2369
2370 if(verifyToken($_POST['userid'])){
2371 if(strlen($_POST['post_title']) < 2){
2372 $GLOBALS['error_message'] = $CORE->_e(array('add','23'));
2373 }else{
2374 // START BUILDING ARRAY OF DATA
2375 $my_post = array();
2376 $my_post['post_type'] = THEME_TAXONOMY."_type";
2377 $my_post['post_title'] = esc_html($_POST['post_title']);
2378 $my_post['post_modified'] = date("Y-m-d h:i:s");
2379 $my_post['city_id'] = $_POST['city_id'];
2380 // STRIP TAGS FROM NON-HTML CONTENT LISTINGS
2381 if(isset($_POST['enhancement'][3]) && $_POST['enhancement'][3] == "on"){
2382 $my_post['post_content'] = stripslashes($_POST['post_content']);
2383 }else{
2384 $my_post['post_content'] = stripslashes(strip_tags(str_replace("http://","",str_replace("https://","",$_POST['post_content']))));
2385 }
2386
2387 $newca = array();
2388 if(is_array($_POST['category'])){
2389 foreach($_POST['category'] as $cat){
2390 if(!is_numeric($cat)){ continue; }
2391 $newca[] = $cat;
2392 }
2393 $my_post['post_category'] = $newca;
2394 }
2395
2396 $total_price_due = 0;
2397 if(is_array($_POST['enhancement'])){
2398 foreach($_POST['enhancement'] as $key=>$val){
2399
2400 if($val == "on" && is_numeric($GLOBALS['CORE_THEME']['enhancement'][$key.'_price']) ){
2401 // NOW CHECK ITS NOT INCLUDED IN THE PACKAGE PRICE
2402 $total_price_due += $GLOBALS['CORE_THEME']['enhancement'][$key.'_price'];
2403 }
2404 }// end foreach
2405 } // end if
2406
2407// ///WORK OUT ANY ADDITIONAL PRICE PER CATEGORY ITEMS
2408 $extra_price_due = 0; $total_price_removed = 0; $current_catprices = get_option('wlt_catprices');
2409 if(is_array($current_catprices)){
2410 /** work out price before (with newly selected cats) ***/
2411 foreach($my_post['post_category'] as $kk=>$catID){
2412 if(isset($current_catprices[$catID])
2413 && ( isset($current_catprices[$catID]) && is_numeric($current_catprices[$catID]) && $current_catprices[$catID] > 0 ) ){
2414 $extra_price_due += $current_catprices[$catID];
2415 }
2416 }
2417
2418 /*** update the total price with the new amount ***/
2419 $total_price_due += $extra_price_due;
2420 //die("new price: ".$extra_price_due." // price removed:".$total_price_removed);
2421 }// end if
2422
2423 if(!isset($_POST['eid'])){
2424 if( $total_price_due == "" || $total_price_due < 1 ){
2425
2426 $admin_default_status = $GLOBALS['CORE_THEME']['default_listing_status'];
2427 if($admin_default_status == "pending"){
2428 $my_post['post_status'] = "pending";
2429 }else{
2430 $my_post['post_status'] = "publish";
2431 }
2432 }else{
2433 $my_post['post_status'] = "pending";
2434 }
2435 }// end if no edit
2436
2437 if(isset($GLOBALS['CORE_THEME']['default_listing_approval']) && $GLOBALS['CORE_THEME']['default_listing_approval'] == 1){
2438 $my_post['post_status'] = "pending";
2439 }
2440
2441 $my_post['post_author'] = $_POST['userid'];
2442
2443 //SAVE DATA
2444 $POSTID = wp_insert_post( hook_add_form_post_save_data($my_post) );
2445 $GLOBALS['PID'] = $POSTID;
2446// // ADD IN DEFAULT ACCES IF SET
2447 if(isset($GLOBALS['CORE_THEME']['default_access']) && is_array($GLOBALS['CORE_THEME']['default_access'])){
2448 add_post_meta($POSTID, 'access', $GLOBALS['CORE_THEME']['default_access']);
2449 }
2450// // DEFAULT FOR NEW LISTINGS
2451 add_post_meta($POSTID, 'hits', 0);
2452 // CREATE SHORTCODES FOR EMAIL
2453 $_POST['title'] = $_POST['post_title'];
2454 $_POST['link'] = get_permalink($POSTID);
2455 $_POST['post_date'] = hook_date(date("Y-m-d h:i:s"));
2456
2457// // SEND NEW LISTING EMAIL
2458 $userdata = get_userdata($_POST['userid']);
2459 $CORE->SENDEMAIL($userdata->data->user_email,'newlisting');
2460 $CORE->SENDEMAIL('admin','admin_newlisting');
2461
2462// // SEND EMAIL ALERT
2463 $CORE->SENDEMAILALERT("wlt_alert_listing_new");
2464
2465 // CHECK FOR USER SUBSCRIPTION EMAILS
2466 if(is_array($my_post['post_category']) && $userdata->data->ID ){
2467 foreach($my_post['post_category'] as $kk=>$catID){
2468 $SQL = "SELECT user_id FROM $wpdb->usermeta WHERE meta_value LIKE ('%*".strip_tags($catID)."*%') AND meta_key='email_subscriptions'";
2469 $sub_results = $wpdb->get_results($SQL);
2470
2471 if (!empty($sub_results) ) {
2472 foreach($sub_results as $val){
2473 $user_info = get_userdata($val->user_id);
2474 $_POST['username'] = $user_info->data->first_name . ' ' . $user_info->data->last_name;
2475 $CORE->SENDEMAIL($val->user_id,'subscription_email');
2476 }
2477 }
2478 }
2479 }
2480
2481// // ADD LOG ENTRY
2482 // $CORE->ADDLOG("<a href='(ulink)'>".$userdata->user_nicename.'</a> added a new listing <a href="(plink)"><b>['.$my_post['post_title'].']</b></a>.', $userdata->ID, $POSTID ,'label-info');
2483 // }
2484
2485// // IF ITS PENDING SEND THE ADMIN AN EMAIL
2486 if($my_post['post_status'] == "pending"){
2487 $CORE->SENDEMAIL('admin','custom',"Listing Pending Approval", "Dear Admin, You have listings pending approval. Please login to your WordPress admin area and approval pending listings.");
2488 }
2489
2490// // POST TAGS
2491 wp_set_post_tags( $POSTID, strip_tags($_POST['post_tags']), false);
2492
2493// // ADD HOOK FOR ANY PLUGIN OPTIONS
2494 hook_add_form_post_save_extra($POSTID);
2495
2496// // UPDATE CAT LIST
2497 wp_set_post_terms( $POSTID, $my_post['post_category'], THEME_TAXONOMY );
2498
2499// // ADD IN CUSTOM FIELDS
2500 //update_post_meta($POSTID, 'packageID', $_POST['packageID']);
2501 update_post_meta($POSTID, 'listing_price', $total_price_due);
2502
2503
2504
2505// // MAKE THIS GLOBAL FOR BOTH EDIT AND NON-EDITS BELOW
2506 $earray = array(
2507 '2' => array('dbkey'=>'featured', 'text'=>'Highlighted Listing'),
2508 '3' => array('dbkey'=>'html', 'text'=>'HTML Listing Content'),
2509 '4' => array('dbkey'=>'visitorcounter', 'text'=>'Visitor Counter'),
2510 '5' => array('dbkey'=>'topcategory', 'text'=>'Top of Category Results Page'),
2511 '6' => array('dbkey'=>'showgooglemap', 'text'=>'Google Map'),
2512 );
2513
2514 // CUSTOM FIELDS FOR enhancementS
2515 $onoff = array();
2516 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][1]) && $_POST['enhancement'][1] == "on" ){ $onoff[1] = "yes"; }else{ $onoff[1] = "no"; }
2517 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][2]) && $_POST['enhancement'][2] == "on" ){ $onoff[2] = "yes"; }else{ $onoff[2] = "no"; }
2518 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][3]) && $_POST['enhancement'][3] == "on" ){ $onoff[3] = "yes"; }else{ $onoff[3] = "no"; }
2519 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][4]) && $_POST['enhancement'][4] == "on" ){ $onoff[4] = "yes"; }else{ $onoff[4] = "no"; }
2520 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][5]) && $_POST['enhancement'][5] == "on" ){ $onoff[5] = "yes"; }else{ $onoff[5] = "no"; }
2521 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][6]) && $_POST['enhancement'][6] == "on" ){ $onoff[6] = "yes"; }else{ $onoff[6] = "no"; }
2522
2523
2524// // NOW LETS UPDATE THE POST FIELDS
2525 update_post_meta($POSTID, 'featured', $onoff[2]); // featured
2526 update_post_meta($POSTID, 'html', 'yes'); // html content
2527 update_post_meta($POSTID, 'visitorcounter', $onoff[4]); // visitor counter
2528 update_post_meta($POSTID, 'topcategory', 'no'); // visitor counter
2529 update_post_meta($POSTID, 'showgooglemap', $onoff[6]); // visitor counter
2530 update_post_meta($POSTID, 'listing_price_due', $total_price_due);
2531
2532 //ADD CITY
2533 update_post_meta($POSTID, 'city_id', $my_post['city_id']);
2534
2535// // SET EXPIRY DATE
2536 if(isset($_POST['listing_expiry_date']) && is_numeric($_POST['listing_expiry_date'])){
2537 update_post_meta($POSTID, 'listing_expiry_date', date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " +".$_POST['listing_expiry_date']." days")));
2538 update_post_meta($POSTID, 'listing_expiry_days', $_POST['listing_expiry_date']);
2539 }
2540
2541// // SAVE THE CUSTOM DATA
2542 if(isset($_POST['custom']) && is_array($_POST['custom'])){
2543 foreach($_POST['custom'] as $key=>$val){ if($key == "listing_expiry_date"){ continue; }
2544
2545 // CLEAN SOME ATTRIBUTES
2546 if(substr($key,0,5) == "price"){
2547 $val = preg_replace('/[^\da-z.]/i', '', $val);
2548 }
2549
2550 // SAVE DATA
2551 if(is_array($val)){
2552 update_post_meta($POSTID, strip_tags($key), $val);
2553 }else{
2554 update_post_meta($POSTID, strip_tags($key), esc_html(strip_tags($val)));
2555 }
2556 }
2557 }
2558
2559// // CHECK FOR FILE UPLOAD
2560
2561 // CHECK FOR FILE UPLOAD
2562 if(isset($_FILES['image']) && is_array($_FILES['image']) ){ // &&
2563 $u=0;
2564
2565 foreach($CORE->reArrayFiles($_FILES['image']) as $file_upload){
2566
2567 if(strlen($file_upload['name']) > 1){
2568 if(isset($_POST['eid']) || $u == 0){
2569
2570 $responce = hook_upload($POSTID, $file_upload,true);
2571 }else{
2572 $responce = hook_upload($POSTID, $file_upload);
2573 }
2574 if(isset($responce['error'])){
2575 $canContinue = false;
2576 $errorMsg = $responce['error'];
2577 }// end if
2578 $u++;
2579 } // end if
2580 } // end foeach
2581 } // end if
2582
2583 $GLOBALS['POSTID'] = $POSTID;
2584 do_action('hook_add_form_post_save');
2585 $location = get_permalink($POSTID);
2586 }
2587 return $location;
2588 }
2589 else {
2590 return "Access error!";
2591 }
2592}
2593
2594
2595
2596 function isFavorite(WP_REST_Request $request){
2597 $userid = $request['uid'];
2598 if(verifyToken($userid)){
2599 $auctionid = $request['auctionid'];
2600 $favlist = get_user_meta($userid,'favorite_list', true);
2601 if(!empty($favlist)){
2602 $result = in_array($auctionid,$favlist);
2603 }
2604 if($result==null || $result==0 || empty($result) || is_null($result)){
2605 $result = false;
2606 }
2607 return $result;
2608 }
2609else {
2610 return 'Access error!';
2611}
2612}
2613
2614
2615 function getDashboardCounts(WP_REST_Request $request){
2616 GLOBAL $wpdb;
2617 $userid = $request['uid'];
2618 if(verifyToken($userid)){
2619 $l=strlen($userid);
2620 $str='"userid"';
2621 $str2='"'.$userid.'"';
2622 $userdata = get_userdata($userid);
2623 // $SQL = "SELECT count(*) AS total_bids FROM ".$wpdb->prefix."posts
2624 // INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
2625 // WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
2626 // AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
2627 // AND mt2.meta_key = 'current_bid_data' AND mt2.meta_value LIKE ('%-".$userid."-%')";
2628 $SQL="SELECT * FROM ".$wpdb->prefix."posts
2629 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
2630 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
2631 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
2632 AND mt2.meta_key = 'current_bid_data' and meta_value like '%".$str.";s:".$l.":".$str2.";%'";
2633 $total_bids = $wpdb->get_results($SQL,ARRAY_A);
2634
2635 foreach ($total_bids as $key => $val){
2636 $id = $total_bids[$key]['ID'];
2637 $total_bids = getMetaNoFilter($id,$total_bids,$key);
2638 if($total_bids[$key]['bidwinnerstring'] == $userdata->user_login){
2639 unset($total_bids[$key]);
2640 }
2641 }
2642
2643 $total_bids_count = count($total_bids);
2644
2645
2646 $SQL = "SELECT count(*) AS total_wins FROM ".$wpdb->prefix."posts
2647 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
2648 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
2649 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
2650 AND mt2.meta_key = 'bidwinnerstring' AND mt2.meta_value LIKE ('%-".$userid."-%')";
2651 $total_wins = $wpdb->get_row($SQL);
2652
2653 $count_selling = $wpdb->get_row("SELECT DISTINCT (SELECT COUNT(*) FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$userid." AND post_status='publish' ) + (SELECT COUNT(*) FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$userid." AND post_status='pending') as total FROM ".$wpdb->prefix."posts");
2654
2655
2656 $count_draft = $wpdb->get_results( "SELECT COUNT(*) as total_draft FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type'
2657 AND p.post_status='draft' AND p.post_author=".$userid."");
2658
2659 $result = array();
2660 $result['total_selling'] = $count_selling->total;
2661 $result['total_draft'] = $count_draft[0]->total_draft;
2662 $result['total_wins'] = $total_wins->total_wins;
2663 $result['total_bids'] = $total_bids_count;
2664
2665 return $result;
2666}
2667else {
2668 return 'Access error!';
2669}
2670}
2671
2672function getDashboardSellingCounts(WP_REST_Request $request){
2673 GLOBAL $wpdb;
2674 $user_id = $request['uid'];
2675 if(verifyToken($user_id)){
2676 $l=strlen($user_id);
2677 $str='"userid"';
2678 $str2='"'.$user_id.'"';
2679 $userdata = get_userdata($user_id);
2680 //active
2681 $pages = 0;
2682 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='publish' ", ARRAY_A);
2683 $nextoffset = count($result);
2684 foreach ($result as $key => $val) {
2685 $id = $result[$key]['ID'];
2686 $result = getMetaNoFilter($id,$result,$key);
2687 if($result[$key]['bidwinnerstring'] !=""){
2688 unset($result[$key]);
2689 continue;
2690 }
2691 if($result[$key]['listing_expiry_date'] ==""){
2692 unset($result[$key]);
2693 continue;
2694 }
2695
2696 if($result[$key]['listing_expiry_date'] < current_time('mysql', 1)){
2697 unset($result[$key]);
2698 continue;
2699 }
2700
2701 $result[$key]['categories']=getCategories($id);
2702 $result[$key]['nextoffset']=$nextoffset;
2703 }
2704 if(count($result) <= 15){
2705 foreach ($result as $key => $val){
2706 $result[$key]['nextoffset']=0;
2707 }
2708 }
2709
2710 $sliced = array_slice($result, $pages);
2711 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
2712 $total_active = count($sliced);
2713
2714 //sold
2715 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='publish' ", ARRAY_A);
2716 $nextoffset = count($result);
2717 foreach ($result as $key => $val) {
2718 $id = $result[$key]['ID'];
2719 $result = getMetaNoFilter($id,$result,$key);
2720 if($result[$key]['bidwinnerstring']==""){
2721 unset($result[$key]);
2722 }else{
2723 $result[$key]['categories']=getCategories($id);
2724 $result[$key]['nextoffset']=$nextoffset;
2725 }
2726 }
2727 // usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
2728 // return array_values($result);
2729 if(count($result) <= 15){
2730 foreach ($result as $key => $val){
2731 $result[$key]['nextoffset']=0;
2732 }
2733 }
2734
2735 $sliced = array_slice($result, $pages);
2736 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
2737 $total_sold = count($sliced);
2738
2739 //pending
2740 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='pending' ", ARRAY_A);
2741 $sliced = array_slice($result, 0);
2742 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
2743 $total_pending = count($sliced);
2744 //not sold
2745 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='publish' ", ARRAY_A);
2746 $nextoffset = count($result);
2747 foreach ($result as $key => $val) {
2748 $id = $result[$key]['ID'];
2749 $result = getMetaNoFilter($id,$result,$key);
2750
2751 if($result[$key]['bidwinnerstring'] !=""){
2752 unset($result[$key]);
2753 continue;
2754 }
2755 if($result[$key]['listing_expiry_date'] !=""){
2756 unset($result[$key]);
2757 continue;
2758 }
2759
2760 $result[$key]['categories']=getCategories($id);
2761 $result[$key]['nextoffset']=$nextoffset;
2762 }
2763 // usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
2764 // return array_values($result);
2765 if(count($result) <= 15){
2766 foreach ($result as $key => $val){
2767 $result[$key]['nextoffset']=0;
2768 }
2769 }
2770
2771 $sliced = array_slice($result, $pages);
2772 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
2773 $total_not_sold = count($sliced);
2774 $result = array();
2775 $result['total_active'] = $total_active;
2776 $result['total_pending'] = $total_pending;
2777 $result['total_sold'] = $total_sold ;
2778 $result['total_not_sold'] = $total_not_sold;
2779
2780 return $result;
2781}
2782else {
2783 return 'Access error!';
2784}
2785}
2786
2787
2788
2789function getBidAucs(WP_REST_Request $request){
2790 GLOBAL $wpdb;
2791 $userid = $request['uid'];
2792 if(verifyToken($userid)){
2793 $offset = $request['offset'];
2794 // $SQL = "SELECT * FROM ".$wpdb->prefix."posts
2795 // INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
2796 // WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
2797 // AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
2798 // AND mt2.meta_key = 'current_bid_data' AND mt2.meta_value LIKE ('%-".$userid."-%') LIMIT 15 OFFSET $offset";
2799 $l=strlen($userid);
2800 // die(var_dump($l));
2801 $str='"userid"';
2802 $str2='"'.$userid.'"';
2803 $userdata = get_userdata($userid);
2804
2805 $SQL="SELECT * FROM ".$wpdb->prefix."posts
2806 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
2807 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
2808 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
2809 AND mt2.meta_key = 'current_bid_data' and meta_value like '%".$str.";s:".$l.":".$str2.";%' ";
2810
2811
2812 $result = $wpdb->get_results($SQL,ARRAY_A);
2813
2814 $nextoffset = count($result);
2815
2816
2817 foreach ($result as $key => $val){
2818 $id = $result[$key]['ID'];
2819 $result = getMetaNoFilter($id,$result,$key);
2820
2821
2822 if($result[$key]['bidwinnerstring'] == $userdata->user_login){
2823 unset($result[$key]);
2824 }else{
2825 $result[$key]['categories']=getCategories($id);
2826 $result[$key]['nextoffset']=$nextoffset;
2827
2828 }
2829
2830
2831 }
2832 if(count($result) <= 15){
2833 foreach ($result as $key => $val){
2834 $result[$key]['nextoffset']=0;
2835 }
2836 }
2837
2838
2839 $sliced = array_slice($result, $offset);
2840 //usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
2841
2842//SORT ARRAYS BY DATE OF USER BIDS
2843 foreach ($sliced as $interval => $value) {
2844 $current_bid_data = $sliced[$interval]['current_bid_data'];
2845 usort($current_bid_data, function($a, $b){ return strcmp ($b['date'], $a['date']); });
2846 $sliced[$interval]['current_bid_data'] = $current_bid_data;
2847 }
2848
2849 foreach ($sliced as $itr => $value) {
2850 $IDauc = $sliced[$itr]['ID'];
2851 $names = array_column($sliced[$itr]['current_bid_data'], 'userid');
2852 $bid_key = array_search($userid, $names);
2853 $keys[$IDauc] = intval($bid_key);
2854 }
2855
2856//foreach ($sliced as $i => $value) {
2857for($i = 0; $j<count($sliced); $i++){
2858 for($j = $i+1; $j<count($sliced); $j++){
2859 $Id_i = $sliced[$i]['ID'];
2860 $Id_j = $sliced[$j]['ID'];
2861 $user_key_data_i = $keys[$Id_i];
2862 $user_key_data_j = $keys[$Id_j];
2863 $date_i = $sliced[$i]['current_bid_data'][$user_key_data_i]['date'];
2864 $date_j = $sliced[$j]['current_bid_data'][$user_key_data_j]['date'];
2865 if(strtotime($date_i) < strtotime($date_j)){
2866
2867 $temp = $sliced[$j];
2868 $sliced[$j] = $sliced[$i];
2869 $sliced[$i] = $temp;
2870 }
2871 }
2872 }
2873
2874
2875
2876 return array_values($sliced);
2877}
2878return 'Access error!';
2879}
2880
2881
2882
2883function getWonAucs(WP_REST_Request $request){
2884 GLOBAL $wpdb;
2885 $userid = $request['uid'];
2886 if(verifyToken($userid)){
2887 $offset = $request['offset'];
2888 $SQL = "SELECT * FROM ".$wpdb->prefix."posts
2889 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
2890 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
2891 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
2892 AND mt2.meta_key = 'bidwinnerstring' AND mt2.meta_value LIKE ('%-".$userid."-%') LIMIT 15 OFFSET $offset";
2893 $result = $wpdb->get_results($SQL,ARRAY_A);
2894
2895 foreach ($result as $key => $val) {
2896 $id = $result[$key]['ID'];
2897 $result[$key]['categories']=getCategories($id);
2898 $result = getMetaNoFilter($id,$result,$key);
2899 }
2900
2901 //usort($result, function($a, $b){ return strcmp ($b['current_bid_data'], $a['current_bid_data']); });
2902
2903 foreach ($result as $interval => $value) {
2904 $current_bid_data = $result[$interval]['current_bid_data'];
2905 usort($current_bid_data, function($a, $b){ return strcmp ($b['date'], $a['date']); });
2906 $result[$interval]['current_bid_data'] = $current_bid_data;
2907 }
2908 usort($result, function($a, $b){ return strcmp ($b['current_bid_data'][0]['date'], $a['current_bid_data'][0]['date']); });
2909
2910 return $result;
2911}
2912else {
2913 return 'Access error!';
2914}
2915}
2916
2917
2918function getAllAucsByUserId(WP_REST_Request $request){
2919 global $wpdb;
2920 $user_id = $request['uid'];
2921 if(verifyToken($user_id)){
2922 $pages = $request['offset'];
2923 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND p.post_status ='publish' LIMIT 15 OFFSET $pages ", ARRAY_A);
2924 foreach ($result as $key => $val) {
2925 $id = $result[$key]['ID'];
2926 $result[$key]['categories']=getCategories($id);
2927 $result = getMetaNoFilter($id,$result,$key);
2928 }
2929 return $result;
2930 }
2931 else {
2932 return 'Access error!';
2933 }
2934}
2935
2936function getSoldAucsByUserId(WP_REST_Request $request){
2937 global $wpdb;
2938 $user_id = $request['uid'];
2939 if(verifyToken($user_id)){
2940 $SQL = "SELECT ID FROM ".$wpdb->prefix."postmeta as meta INNER JOIN ".$wpdb->prefix."posts p ON p.ID=meta.post_id WHERE meta_key='bidwinnerstring' and p.post_author=".$user_id." and meta_value <> ''";
2941 $ids = $wpdb->get_results($SQL);
2942 foreach ($ids as $key) {
2943 $auctionId = $key->ID;
2944 // $post[$auctionId] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."posts WHERE ID=$auctionId AND post_type = 'listing_type' and post_status = 'publish'", ARRAY_A);
2945 $post[$auctionId] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."posts WHERE ID=$auctionId AND post_type = 'listing_type'", ARRAY_A);
2946 if($post[$auctionId]!= null){
2947 $post[$auctionId ]['categories'] = getCategories($auctionId);
2948 $post = getMetaNoFilter($auctionId,$post,$auctionId);
2949 }else{
2950 unset($post[$auctionId]);
2951 }
2952 }
2953 return array_values($post);
2954}
2955else {
2956 return 'Access error!';
2957}
2958}
2959
2960function getBankInfo(WP_REST_Request $request){
2961 global $wpdb;
2962 $user_id = $request['uid'];
2963 if(verifyToken($user_id)){
2964 $bank_name = $wpdb->get_row("SELECT meta_value FROM ".$wpdb->prefix."usermeta where user_id=".$user_id." and meta_key='bank_name'");
2965 $account_no = $wpdb->get_row("SELECT meta_value FROM ".$wpdb->prefix."usermeta where user_id=".$user_id." and meta_key='account_no'");
2966 $account_iban = $wpdb->get_row("SELECT meta_value FROM ".$wpdb->prefix."usermeta where user_id=".$user_id." and meta_key='account_iban'");
2967 $account_name = $wpdb->get_row("SELECT meta_value FROM ".$wpdb->prefix."usermeta where user_id=".$user_id." and meta_key='account_name'");
2968 $account_more = $wpdb->get_row("SELECT meta_value FROM ".$wpdb->prefix."usermeta where user_id=".$user_id." and meta_key='account_more'");
2969 $result = array();
2970 $result['bank_name'] = $bank_name->meta_value;
2971 $result['account_no'] = $account_no->meta_value;
2972 $result['account_iban'] = $account_iban->meta_value;
2973 $result['account_name'] = $account_name->meta_value;
2974 $result['account_more'] = $account_more->meta_value;
2975 return $result;
2976 }
2977 else {
2978 return 'Access error!';
2979 }
2980}
2981
2982function updateBankInfo(WP_REST_Request $request){
2983 global $wpdb;
2984 $user_id = $request['uid'];
2985 if(verifyToken($user_id)){
2986 $bank_name = $request['bank_name'];
2987 $account_no = $request['account_no'];
2988 $account_iban = $request['account_iban'];
2989 $account_name = $request['account_name'];
2990 $account_more = $request['account_more'];
2991 update_user_meta($user_id, 'bank_name', $bank_name);
2992 update_user_meta($user_id, 'account_no', $account_no);
2993 update_user_meta($user_id, 'account_iban', $account_iban);
2994 update_user_meta($user_id, 'account_name', $account_name);
2995 update_user_meta($user_id, 'account_more', $account_more);
2996 $result = array('status' => 'success',
2997 'message' =>'Bank info updated');
2998 return $result;
2999 }
3000 else {
3001 return 'Access error';
3002 }
3003}
3004
3005function updatePhoneNumber (WP_REST_Request $request){
3006 global $wpdb;
3007 $new_number = $request['new_number'];
3008 $userid = $request['uid'];
3009 if(verifyToken($userid)){
3010 $locale = $request['locale'];
3011 if($new_number != 0){
3012 $SQL = "SELECT * FROM ".$wpdb->prefix."smsregister
3013 WHERE phone_number='".addslashes($new_number)."' AND status=1";
3014
3015 $check = $wpdb->get_row($SQL);
3016 if (!$check) {
3017 $code = mt_rand(1000, 9999);
3018 if($locale == "arabic"){
3019 $msg = sprintf('%s Ù„ØªØØ¯ÙŠØ« رقم الجوال الرجاء ادخال الرمز ' , $code);
3020 }else{
3021 $msg = sprintf('Please use the code %s to update your mobile number', $code);
3022 }
3023 $url = 'http://api.unifonic.com/rest/Messages/Send';
3024
3025 $params = array (
3026 'Recipient' => $new_number,
3027 'Body' => $msg,
3028 'AppSid' => 'mLPnnX8zWRUlFIVCXFH5wOszKHBGfk',
3029 'encoding' => 'encoding=UTF8',
3030 'SenderID' => 'Kayish',
3031 );
3032
3033 $postString = http_build_query($params, '', '&');
3034
3035 $additional_headers = array(
3036 'Authorization: Basic bWhvdXNlIDpNaG91c2VfMTE=',
3037 'Content-Type: application/x-www-form-urlencoded'
3038 );
3039
3040 $ch = curl_init($url);
3041 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
3042 curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
3043 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
3044 //curl_setopt($ch, CURLOPT_HTTPHEADER, $additional_headers);
3045
3046 $server_output = curl_exec ($ch);
3047 $resp = json_decode($server_output,true);
3048 if ($resp['success'] == true) {
3049 $userarray = get_userdata($userid);
3050 $wpdb->query("INSERT INTO ".$wpdb->prefix."smsregister (username, phone_number, sent_code, sent_sms, last_sent, status)
3051 VALUES ('".addslashes($userarray->data->user_login)."', '".$new_number."', ".$code.", 1, '".time(TRUE)."', 0);");
3052 return $server_output;
3053 } else {
3054 $result = array( 'status' => 'error', 'message' => 'SMS server error');
3055 return $result;
3056 }
3057
3058 } else {
3059 $result = array( 'status' => 'error', 'message' => 'This phone number is already registered. Please enter a new phone number');
3060 return $result;
3061 }
3062 }else{
3063 $result = array('status' => 'error',
3064 'message' =>'Phone number is invalid');
3065 return $result;
3066 }
3067}
3068else {
3069 return 'Access error!';
3070}
3071}
3072
3073
3074function validateCodeUpdate (WP_REST_Request $request) {
3075 global $wpdb;
3076 $phone_number = $request["phonenumber"];
3077 $code = $request["code"];
3078 $user_id = $request["uid"];
3079 if(verifyToken($user_id)){
3080 if ($phone_number and $code) {
3081 $info = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."smsregister WHERE phone_number= $phone_number and sent_code=$code and status=0",ARRAY_A);
3082 if(!empty($info)){
3083 $result = $wpdb->query("UPDATE ".$wpdb->prefix."smsregister SET status=1 WHERE phone_number= $phone_number and sent_code=$code");
3084 if($result==1){
3085 $result_update = update_user_meta($user_id, 'phone', $phone_number);
3086
3087 $result = array( 'status' => 'success', 'message' => 'Phone number updated');
3088 return $result;
3089 }else{
3090 $result = array( 'status' => 'error', 'message' => 'Registration error');
3091 return $result;
3092 }
3093 }else{
3094 $result = array( 'status' => 'error', 'message' => 'Incorrect Verification code or phone number, please try again');
3095 return $result;
3096 }
3097}else{
3098 $result = array( 'status' => 'error', 'message' => 'No data found');
3099 return $result;
3100}
3101}
3102else {
3103 return 'Access error!';
3104}
3105}
3106
3107function getUsersFeedbacks(WP_REST_Request $request){
3108 global $wpdb;
3109 $userid = $request['uid'];
3110 if(verifyToken($userid)){
3111 $feedbacks = $wpdb->get_results("SELECT ID, post_author, post_date, post_date_gmt, post_content, post_title, guid, post_type
3112 FROM ".$wpdb->prefix."postmeta m INNER JOIN ".$wpdb->prefix."posts p on p.ID = m.post_id WHERE post_status = 'publish' and meta_key='uid' and meta_value=".$userid."", ARRAY_A);
3113
3114 foreach ($feedbacks as $key => $value) {
3115
3116 $id = $feedbacks[$key]['ID'];
3117 $userid = $feedbacks[$key]['post_author'];
3118 $scores = $wpdb->get_row("SELECT meta_value as score
3119 FROM ".$wpdb->prefix."postmeta WHERE post_id=$id AND meta_key='score'");
3120
3121 $feedbacks[$key]['stars'] = $scores->score;
3122
3123 $userdata = get_userdata($userid);
3124 $feedbacks[$key]['author_username'] = $userdata->data->display_name;
3125
3126 $html=get_avatar($userid);
3127 $doc = new DOMDocument();
3128 $doc->loadHTML($html);
3129 $xpath = new DOMXPath($doc);
3130 $src = $xpath->evaluate("string(//img/@src)");
3131 $feedbacks[$key]['author_avatar'] = $src;
3132 $auct_id=get_post_meta($id,'pid',true);
3133 $feedbacks[$key]['auction_id']=$auct_id;
3134 $feedbacks[$key]['auction_title']=get_post_field('post_title',$auct_id);
3135 }
3136 return $feedbacks;
3137 }
3138 else {
3139 return 'Access error';
3140 }
3141}
3142
3143function getUsersSendedFeedbacks(WP_REST_Request $request){
3144 global $wpdb;
3145 $userid = $request['uid'];
3146 if(verifyToken($userid)){
3147 $feedbacks = $wpdb->get_results("SELECT DISTINCT ID, post_author, post_date, post_date_gmt, post_content, post_title, guid, post_type
3148 FROM ".$wpdb->prefix."postmeta m INNER JOIN ".$wpdb->prefix."posts p on p.ID = m.post_id WHERE post_status = 'publish' and post_type='wlt_feedback' and post_author=$userid", ARRAY_A);
3149
3150 foreach ($feedbacks as $key => $value) {
3151 $id = $feedbacks[$key]['ID'];
3152
3153 $scores = $wpdb->get_row("SELECT meta_value as score
3154 FROM ".$wpdb->prefix."postmeta WHERE post_id=$id AND meta_key='score'");
3155 $feedbacks[$key]['stars'] = $scores->score;
3156
3157 $author_auct_id = $wpdb->get_row("SELECT meta_value as userid
3158 FROM ".$wpdb->prefix."postmeta WHERE post_id=$id AND meta_key='uid'");
3159
3160 //$userid = $feedbacks[$key]['post_author'];
3161
3162
3163
3164 $userdata = get_userdata($author_auct_id->userid);
3165 // var_dump($userdata);
3166 $feedbacks[$key]['author_username'] = $userdata->data->display_name;
3167
3168 $html=get_avatar($author_auct_id->userid);
3169 $doc = new DOMDocument();
3170 $doc->loadHTML($html);
3171 $xpath = new DOMXPath($doc);
3172 $src = $xpath->evaluate("string(//img/@src)");
3173
3174 $feedbacks[$key]['author_avatar'] = $src;
3175
3176 $auct_id=get_post_meta($id,'pid',true);
3177 $feedbacks[$key]['auction_id']=$auct_id;
3178 $feedbacks[$key]['auction_title']=get_post_field('post_title',$auct_id);
3179
3180 }
3181 return $feedbacks;
3182 }
3183 else {
3184 return 'Access error!';
3185 }
3186}
3187
3188function getSellingAucsByUserId(WP_REST_Request $request){
3189 global $wpdb;
3190 $user_id = $request['uid'];
3191 if(verifyToken($user_id)){
3192 $pages = $request['offset'];
3193 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." LIMIT 15 OFFSET $pages ", ARRAY_A);
3194 foreach ($result as $key => $val) {
3195 $id = $result[$key]['ID'];
3196 $result[$key]['categories']=getCategories($id);
3197 $result = getMetaNoFilter($id,$result,$key);
3198 }
3199 usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3200 return $result;
3201 }
3202 else {
3203 return 'Access error!';
3204 }
3205}
3206
3207function getSellingPendingAucsByUserId(WP_REST_Request $request){
3208 global $wpdb;
3209
3210
3211 $user_id = $request['uid'];
3212 if(verifyToken($user_id)){
3213 $pages = $request['offset'];
3214 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='pending' ", ARRAY_A);
3215
3216 foreach ($result as $key => $val) {
3217 $id = $result[$key]['ID'];
3218 $pay=getPayInf($user_id,$id);
3219
3220 array_push($result[$key]['is_paid']);
3221 $result[$key]['is_paid']=$pay;
3222
3223 }
3224
3225
3226 foreach ($result as $key => $val) {
3227 $id = $result[$key]['ID'];
3228
3229 $result[$key]['categories']=getCategories($id);
3230 $result = getMetaNoFilter($id,$result,$key);
3231 }
3232
3233
3234
3235
3236
3237
3238 // usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3239 // return $result;
3240 if(count($result) <= 15){
3241 foreach ($result as $key => $val){
3242 $result[$key]['nextoffset']=0;
3243 }
3244 }
3245
3246 $sliced = array_slice($result, $pages);
3247 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3248 return array_values($sliced);
3249}
3250else {
3251 return 'Access error!';
3252}
3253}
3254
3255function getSellingSoldAucsByUserId(WP_REST_Request $request){
3256 global $wpdb;
3257 $user_id = $request['uid'];
3258 if(verifyToken($user_id)){
3259 $pages = $request['offset'];
3260 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='publish' ", ARRAY_A);
3261 $nextoffset = count($result);
3262 foreach ($result as $key => $val) {
3263 $id = $result[$key]['ID'];
3264 $result = getMetaNoFilter($id,$result,$key);
3265 if($result[$key]['bidwinnerstring']==""){
3266 unset($result[$key]);
3267 }else{
3268 $result[$key]['categories']=getCategories($id);
3269 $result[$key]['nextoffset']=$nextoffset;
3270 }
3271 }
3272 // usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3273 // return array_values($result);
3274 if(count($result) <= 15){
3275 foreach ($result as $key => $val){
3276 $result[$key]['nextoffset']=0;
3277 }
3278 }
3279
3280 $sliced = array_slice($result, $pages);
3281 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3282 return array_values($sliced);
3283}
3284else {
3285 return 'Access error!';
3286}
3287}
3288
3289function getSellingNotSoldAucsByUserId(WP_REST_Request $request){
3290 global $wpdb;
3291 $user_id = $request['uid'];
3292 if(verifyToken($user_id)){
3293 $pages = $request['offset'];
3294 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='publish' ", ARRAY_A);
3295 $nextoffset = count($result);
3296 foreach ($result as $key => $val) {
3297 $id = $result[$key]['ID'];
3298 $result = getMetaNoFilter($id,$result,$key);
3299
3300 if($result[$key]['bidwinnerstring'] !=""){
3301 unset($result[$key]);
3302 continue;
3303 }
3304 if($result[$key]['listing_expiry_date'] !=""){
3305 unset($result[$key]);
3306 continue;
3307 }
3308
3309 $result[$key]['categories']=getCategories($id);
3310 $result[$key]['nextoffset']=$nextoffset;
3311 }
3312 // usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3313 // return array_values($result);
3314 if(count($result) <= 15){
3315 foreach ($result as $key => $val){
3316 $result[$key]['nextoffset']=0;
3317 }
3318 }
3319
3320 $sliced = array_slice($result, $pages);
3321 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3322 return array_values($sliced);
3323}
3324else {
3325 return 'Access error!';
3326}
3327}
3328
3329function getSellingCurrentAucsByUserId(WP_REST_Request $request){
3330 global $wpdb;
3331 $user_id = $request['uid'];
3332 if(verifyToken($user_id)){
3333 $pages = $request['offset'];
3334 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND post_status='publish' ", ARRAY_A);
3335 $nextoffset = count($result);
3336 foreach ($result as $key => $val) {
3337 $id = $result[$key]['ID'];
3338 $result = getMetaNoFilter($id,$result,$key);
3339 if($result[$key]['bidwinnerstring'] !=""){
3340 unset($result[$key]);
3341 continue;
3342 }
3343 if($result[$key]['listing_expiry_date'] ==""){
3344 unset($result[$key]);
3345 continue;
3346 }
3347
3348 if($result[$key]['listing_expiry_date'] < current_time('mysql', 1)){
3349 unset($result[$key]);
3350 continue;
3351 }
3352
3353 $result[$key]['categories']=getCategories($id);
3354 $result[$key]['nextoffset']=$nextoffset;
3355 }
3356
3357
3358 // usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3359 // return array_values($result);
3360 if(count($result) <= 15){
3361 foreach ($result as $key => $val){
3362 $result[$key]['nextoffset']=0;
3363 }
3364 }
3365
3366 $sliced = array_slice($result, $pages);
3367 usort($sliced, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
3368 return array_values($sliced);
3369}
3370else {
3371 return 'Access error!';
3372}
3373}
3374
3375
3376function getEnchacementsPrice(WP_REST_Request $request){
3377
3378 global $CORE;
3379 $earray = array(
3380 '2' => array('dbkey'=>'featured', 'text'=>'Highlighted Listing'),
3381 '3' => array('dbkey'=>'html', 'text'=>'HTML Listing Content'),
3382 '4' => array('dbkey'=>'visitorcounter', 'text'=>'Visitor Counter'),
3383 '5' => array('dbkey'=>'topcategory', 'text'=>'Top of Category Results Page'),
3384 '6' => array('dbkey'=>'showgooglemap', 'text'=>'Google Map'),
3385 );
3386
3387 foreach ($earray as $key => $value) {
3388 $GLOBALS['CORE_THEME']['enhancement'][$earray[$key]['dbkey']] = $GLOBALS['CORE_THEME']['enhancement'][$key.'_price'];
3389 }
3390
3391 return $GLOBALS['CORE_THEME']['enhancement'];
3392
3393}
3394
3395function getWinAucsForFeedback(WP_REST_Request $request){
3396 global $wpdb;
3397 $userid = $request['uid'];
3398 if(verifyToken($userid)){
3399 $SQL = "SELECT * FROM ".$wpdb->prefix."posts
3400 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON (".$wpdb->prefix."posts.ID = mt2.post_id)
3401 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type'
3402 AND ( ".$wpdb->prefix."posts.post_status = 'publish' )
3403 AND mt2.meta_key = 'bidwinnerstring' AND mt2.meta_value LIKE ('%-".$userid."-%') ";
3404
3405 $wonAucs = $wpdb->get_results($SQL,ARRAY_A);
3406 $feedbacks=array();
3407 foreach ($wonAucs as $key => $value) {
3408 $id = $wonAucs[$key]['ID'];
3409 $feedback = $wpdb->get_row("SELECT post_id as feedback_id, meta_value as auctionid FROM ".$wpdb->prefix."postmeta WHERE meta_key='pid' and meta_value=".$id."");
3410 if(empty($feedback)){
3411 $feedback = array("feedback_id" => "nofeedback", "auctionid"=> $id);
3412 }
3413 array_push($feedbacks, $feedback);
3414
3415 }
3416 $key=0;
3417
3418
3419 foreach ($feedbacks as $key => $value) {
3420 $feedback_postId = $feedbacks[$key]->feedback_id;
3421 $author_id = get_post_field('post_author', $feedback_postId);
3422 if($author_id == $userid){
3423 unset($feedbacks[$key]);
3424 }
3425 }
3426 $key=0;
3427
3428 $needFeedback = array();
3429
3430 foreach ($feedbacks as $key => $value) {
3431 $id = $feedbacks[$key]['auctionid'];
3432 $needFeedback[$key]['auctionid'] = $id;
3433 $needFeedback[$key]['auction_title'] = get_post_field('post_title', $id);
3434 $needFeedback[$key]['price_current'] = get_post_meta( $id, 'price_current', true );
3435 $thumbnailID = get_post_meta( $id, '_thumbnail_id', true );
3436 $thumbnail = wp_get_attachment_image_src($thumbnailID, 'post' );
3437 $needFeedback[$key]['thumbnail'] = $thumbnail[0];
3438
3439 $seller_id = get_post_field('post_author', $id);
3440 $userdata = get_userdata($seller_id);
3441 $needFeedback[$key]['author_username'] = $userdata->data->display_name;
3442
3443 // $seller_id = get_post_field('post_author', $id);
3444 // $userdata = get_userdata($seller_id);
3445 // $needFeedback[$key]['seller_username'] = $userdata->data->display_name;
3446 // $html=get_avatar($seller_id);
3447 // $doc = new DOMDocument();
3448 // $doc->loadHTML($html);
3449 // $xpath = new DOMXPath($doc);
3450 // $src = $xpath->evaluate("string(//img/@src)");
3451 // $needFeedback[$key]['seller_avatar'] = $src;
3452 }
3453 $key=0;
3454 return array_values($needFeedback);
3455 }
3456 else {
3457 return 'Access error!';
3458 }
3459}
3460
3461
3462
3463
3464 function sendPush ($user_id, $title, $body){
3465
3466 $notification = array('title' =>$title , 'body' => $body );
3467 $token = get_user_meta($user_id, 'device_token', true);
3468 $arrayToSend = array('to' => $token, 'notification' => $notification, /*'data' => $notification*/ );
3469
3470
3471 $json = json_encode($arrayToSend);
3472
3473
3474 //Setup headers:
3475 $headers = array();
3476 $headers[] = 'Content-Type: application/json';
3477 $headers[] = 'Authorization: key=AIzaSyCqmGSWYml8fBa-qo0LWNUL1gLbdSafJ0g'; // key here
3478 $ch = curl_init("https://fcm.googleapis.com/fcm/send");
3479
3480 //Setup curl, add headers and post parameters.
3481 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
3482 curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
3483 curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
3484
3485 //Send the request
3486 $response = curl_exec($ch);
3487 $info = curl_getinfo($ch);
3488 curl_close($ch);
3489
3490
3491 }
3492
3493function sendP (WP_REST_Request $request){
3494 //The device token.
3495
3496 $user_id = $request['uid'];
3497 $title = $request['title'];
3498 $body = $request['body'];
3499
3500 //Ð´Ð»Ñ Ñ‚ÐµÑта
3501 //$semd=sendPushP($request['uid'],$request['title'],$request['body']);
3502
3503 $token = get_user_meta($user_id, 'device_token' , true);
3504
3505
3506 //Creating the notification array.
3507 $notification = array('title' =>$title , 'body' => $body );
3508 $data = json_encode($notification);
3509 //This array contains, the token and the notification. The 'to' attribute stores the token.
3510 $arrayToSend = array('to' => $token, 'notification' => $notification, /*'data' => $notification */);
3511
3512//
3513 //Generating JSON encoded string form the above array.
3514 $json = json_encode($arrayToSend);
3515
3516
3517 //Setup headers:
3518 $headers = array();
3519 $headers[] = 'Content-Type: application/json';
3520 $headers[] = 'Authorization: key=AIzaSyCqmGSWYml8fBa-qo0LWNUL1gLbdSafJ0g'; // key here
3521 $ch = curl_init("https://fcm.googleapis.com/fcm/send");
3522 //Setup curl, add headers and post parameters.
3523 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
3524 curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
3525 curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
3526 //Send the request
3527 $response = curl_exec($ch);
3528 //Close request
3529 curl_close($ch);
3530 return $response;
3531}
3532
3533 function sendPushP ($user_id, $title, $body){
3534
3535 $dbh = new \PDO('mysql:host=localhost;dbname=mazadhou_nmazad;charset=utf8', 'mazadhou_mazad', 'Alhutami0561!');
3536 //$dbh = new \PDO('mysql:host=localhost;dbname=mazadhou_nmazad;charset=utf8', 'root', '');
3537 $gettoken = $dbh->prepare("SELECT * FROM `mazadhou_nmazad`.`wp_usermeta` WHERE user_id=:userTo AND (CONVERT(`umeta_id` USING utf8) LIKE '%device_token%' OR CONVERT(`user_id` USING utf8) LIKE '%device_token%' OR CONVERT(`meta_key` USING utf8) LIKE '%device_token%' OR CONVERT(`meta_value` USING utf8) LIKE '%device_token%')");
3538 $gettoken->bindParam(':userTo', $user_id);
3539 $gettoken->execute();
3540 $gettoken=$gettoken->fetch();
3541 $token=$gettoken['3'];
3542
3543
3544 $data=json_encode($body);
3545
3546
3547 $client = new Client(__DIR__.'/mazad-ab6a4-firebase-adminsdk-7nju9-8071b40570.json');
3548
3549 $recipient = new Recipient();
3550
3551 // Either Notification or Data (or both) instance should be created
3552 $notification = new Notification();
3553
3554 $recipient -> setSingleREcipient($token);
3555
3556 // Setup Notificaition title and body
3557 $notification -> setNotification($title, $data);
3558
3559 // $androidConfig = new Config\AndroidConfig();
3560 // $androidConfig -> setPriority(Config\AndroidConfig::PRIORITY_HIGH);
3561 // $client -> build($recipient, $notification, null, $androidConfig);
3562 //
3563 //
3564 //
3565 // $apnsConfig = new Config\APNsConfig();
3566 // $apnsConfig -> setPriority(Config\APNsConfig::PRIORITY_HIGH);
3567 // $client -> build($recipient, $notification, null, $apnsConfig);
3568
3569 // Build FCM request payload
3570 $client -> build($recipient, $notification);
3571
3572 $response = $client -> fire();// You can check the result
3573
3574// echo "<pre>";
3575// var_dump($response);exit;
3576 // If successful, true will be returned
3577 // If not, error message will be returned
3578 return $response;
3579}
3580
3581
3582
3583
3584 function addDeviceToken(WP_REST_Request $request) {
3585 $userid = $request['uid'];
3586 $token = $request['device_token'];
3587 $result = update_user_meta($userid,'device_token',$token);
3588 return $result;
3589 }
3590
3591function addFeedBack(WP_REST_Request $request){
3592 global $CORE, $wpdb;
3593
3594 $userid = $request ['uid'];
3595 if(verifyToken($userid)){
3596 $auctionid = $request ['auctionid'];
3597 $score = $request ['score'];
3598
3599 $SQL = "SELECT ID FROM ".$wpdb->prefix."posts
3600 INNER JOIN ".$wpdb->prefix."postmeta AS mt2 ON ".$wpdb->prefix."posts.ID = mt2.post_id
3601 WHERE ".$wpdb->prefix."posts.post_type = 'listing_type' AND ".$wpdb->prefix."posts.ID = $auctionid
3602 AND mt2.meta_key = 'bidwinnerstring' AND mt2.meta_value LIKE ('%-".$userid."-%')";
3603
3604 $wonAucs = $wpdb->get_results($SQL,ARRAY_A);
3605
3606 if($auctionid == $wonAucs[0]['ID']){
3607
3608 if($CORE->FEEDBACKEXISTS($auctionid, $userid) == true){
3609 $result = array( 'status' => 'error', 'message' => 'Feedback is already exists');
3610 }else{
3611
3612 $my_post = array();
3613 $my_post['post_title'] = strip_tags(strip_tags($request['subject']));
3614 $my_post['post_content'] = strip_tags(strip_tags($request['message']));
3615 $my_post['post_excerpt'] = "";
3616 $my_post['post_status'] = "publish";
3617 $my_post['post_type'] = "wlt_feedback";
3618 $my_post['post_author'] = $userid;
3619 $POSTID = wp_insert_post( $my_post );
3620
3621 // GET THE LISTING DATA
3622 $feedback_postdata = get_post($auctionid);
3623
3624 // CUSTOM FIELDS
3625 add_post_meta($POSTID, "pid", $auctionid);
3626 add_post_meta($POSTID, "score", $score );
3627 add_post_meta($POSTID, "uid", $feedback_postdata->post_author);
3628 add_post_meta($POSTID, "auid", $userid);
3629
3630 // ADD FEEDBACK RATING TO THE POST ITSELF
3631 $fback = $CORE->FEEDBACKSCORE($auctionid);
3632 $tscore = $fback['score']*5/100;
3633 update_post_meta($auctionid, 'rating_total', $tscore);
3634 // SEND EMAIL
3635 $_POST['title'] = $feedback_postdata->post_title;
3636 $_POST['link'] = get_permalink($feedback_postdata->ID);
3637 $CORE->SENDEMAIL($feedback_postdata->post_author,'newfeedback');
3638
3639 //send push
3640 $lang_user=get_user_meta($feedback_postdata->post_author,'language',true);
3641 if($lang_user=="EN") {
3642 $messageWithName = "you received a new feedback from" . get_user_meta($userid, 'nickname', true);
3643 $notification_body = GetNotificationMessageForAuction($auctionid, NULL, $messageWithName,
3644 NULL, "Feedback Received", "Auction name (EN)") ;
3645
3646 }
3647 else {
3648 $messageWithName = get_user_meta($userid, 'nickname', true)." "."لقد تلقيت تقييم جديد من المستخدم";
3649 $notification_body = GetNotificationMessageForAuction($auctionid, NULL, $messageWithName,
3650 NULL, "تقييم جديد", "Auction name (EN)") ;
3651 }
3652
3653 $notification_title = '';
3654 $notification_user_id = $feedback_postdata->post_author;
3655 sendPushP($notification_user_id, $notification_title, $notification_body);
3656
3657 $result = array( 'status' => 'success', 'message' => 'Feedback success');
3658
3659 }
3660 }else{
3661 $result = array( 'status' => 'error', 'message' => 'You are not winner');
3662 }
3663 return $result;
3664 }
3665 else {
3666 return 'Access error!';
3667 }
3668 }
3669
3670 function getAllActiveCities(WP_REST_Request $request) {
3671 global $wpdb;
3672 $SQL = "SELECT * FROM ".$wpdb->prefix."cities WHERE status=1";
3673 $result = $wpdb->get_results($SQL,ARRAY_A);
3674 return $result;
3675 }
3676
3677 function getAllActiveCountries(WP_REST_Request $request) {
3678 global $wpdb;
3679 $SQL = "SELECT * FROM ".$wpdb->prefix."countries WHERE status=1";
3680 $result = $wpdb->get_results($SQL,ARRAY_A);
3681 return $result;
3682 }
3683
3684 function getCountryById(WP_REST_Request $request) {
3685 global $wpdb;
3686 $countryid = $request['countryid'];
3687 $SQL = "SELECT * FROM ".$wpdb->prefix."countries WHERE id = $countryid";
3688 $result = $wpdb->get_row($SQL,ARRAY_A);
3689 return $result;
3690 }
3691
3692 function getCitiesByCountryId(WP_REST_Request $request) {
3693 global $wpdb;
3694 $countryid = $request['countryid'];
3695 $SQL = "SELECT * FROM ".$wpdb->prefix."cities WHERE status=1 AND country_id = $countryid";
3696 $result = $wpdb->get_results($SQL,ARRAY_A);
3697 return $result;
3698 }
3699
3700
3701 function editAuction(WP_REST_Request $request){
3702
3703 global $CORE, $wpdb;
3704 //$_POST['enhancement_3'] - HTML
3705 if(verifyToken($_POST['userid'])){
3706 if(strlen($_POST['post_title']) < 2){
3707 $GLOBALS['error_message'] = $CORE->_e(array('add','23'));
3708 }else{
3709 // START BUILDING ARRAY OF DATA
3710 $my_post = array();
3711 $my_post['ID'] = $_POST['auctionId'];
3712 $my_post['post_type'] = THEME_TAXONOMY."_type";
3713 $my_post['post_title'] = esc_html($_POST['post_title']);
3714 $my_post['post_modified'] = date("Y-m-d h:i:s");
3715 $my_post['city_id'] = $_POST['city_id'];
3716
3717
3718 // STRIP TAGS FROM NON-HTML CONTENT LISTINGS
3719 if(isset($_POST['enhancement'][3]) && $_POST['enhancement'][3] == "on"){
3720 $my_post['post_content'] = stripslashes($_POST['post_content']);
3721 }else{
3722 $my_post['post_content'] = stripslashes(strip_tags(str_replace("http://","",str_replace("https://","",$_POST['post_content']))));
3723 }
3724
3725 $newca = array();
3726 if(is_array($_POST['category'])){
3727 foreach($_POST['category'] as $cat){
3728 if(!is_numeric($cat)){ continue; }
3729 $newca[] = $cat;
3730 }
3731 $my_post['post_category'] = $newca;
3732 }
3733
3734 $total_price_due = 0;
3735 if(is_array($_POST['enhancement'])){
3736 foreach($_POST['enhancement'] as $key=>$val){
3737
3738 if($val == "on" && is_numeric($GLOBALS['CORE_THEME']['enhancement'][$key.'_price']) ){
3739 // NOW CHECK ITS NOT INCLUDED IN THE PACKAGE PRICE
3740 $total_price_due += $GLOBALS['CORE_THEME']['enhancement'][$key.'_price'];
3741 }
3742 }// end foreach
3743 } // end if
3744
3745// ///WORK OUT ANY ADDITIONAL PRICE PER CATEGORY ITEMS
3746 $extra_price_due = 0; $total_price_removed = 0; $current_catprices = get_option('wlt_catprices');
3747 if(is_array($current_catprices)){
3748 /** work out price before (with newly selected cats) ***/
3749 foreach($my_post['post_category'] as $kk=>$catID){
3750 if(isset($current_catprices[$catID])
3751 && ( isset($current_catprices[$catID]) && is_numeric($current_catprices[$catID]) && $current_catprices[$catID] > 0 ) ){
3752 $extra_price_due += $current_catprices[$catID];
3753 }
3754 }
3755
3756 /*** update the total price with the new amount ***/
3757 $total_price_due += $extra_price_due;
3758 //die("new price: ".$extra_price_due." // price removed:".$total_price_removed);
3759 }// end if
3760
3761 if(!isset($_POST['eid'])){
3762 if( $total_price_due == "" || $total_price_due < 1 ){
3763
3764 $admin_default_status = $GLOBALS['CORE_THEME']['default_listing_status'];
3765 if($admin_default_status == "pending"){
3766 $my_post['post_status'] = "pending";
3767 }else{
3768 $my_post['post_status'] = "publish";
3769 }
3770 }else{
3771 $my_post['post_status'] = "pending";
3772 }
3773 }// end if no edit
3774
3775 if(isset($GLOBALS['CORE_THEME']['default_listing_approval']) && $GLOBALS['CORE_THEME']['default_listing_approval'] == 1){
3776 $my_post['post_status'] = "pending";
3777 }
3778
3779 $my_post['post_author'] = $_POST['userid'];
3780
3781 //SAVE DATA
3782 $post_info = get_post($my_post['ID']);
3783
3784
3785 if(empty($post_info)){
3786 $result = array('status' => 'error','message' => 'Auction not found');
3787 return $result;
3788 }else{
3789
3790 if($post_info->post_status == "draft"){
3791 $my_post['post_status'] = "draft";
3792 }
3793
3794 $POSTID = wp_update_post(hook_add_form_post_save_data($my_post));
3795 }
3796 $GLOBALS['PID'] = $POSTID;
3797// // ADD IN DEFAULT ACCES IF SET
3798 if(isset($GLOBALS['CORE_THEME']['default_access']) && is_array($GLOBALS['CORE_THEME']['default_access'])){
3799 update_post_meta($POSTID, 'access', $GLOBALS['CORE_THEME']['default_access']);
3800 }
3801
3802
3803 // CHECK FOR USER SUBSCRIPTION EMAILS
3804 if(is_array($my_post['post_category']) && $userdata->data->ID ){
3805 foreach($my_post['post_category'] as $kk=>$catID){
3806 $SQL = "SELECT user_id FROM $wpdb->usermeta WHERE meta_value LIKE ('%*".strip_tags($catID)."*%') AND meta_key='email_subscriptions'";
3807 $sub_results = $wpdb->get_results($SQL);
3808
3809 if (!empty($sub_results) ) {
3810 foreach($sub_results as $val){
3811 $user_info = get_userdata($val->user_id);
3812 $_POST['username'] = $user_info->data->first_name . ' ' . $user_info->data->last_name;
3813 $CORE->SENDEMAIL($val->user_id,'subscription_email');
3814 }
3815 }
3816 }
3817 }
3818
3819// // ADD LOG ENTRY
3820 // $CORE->ADDLOG("<a href='(ulink)'>".$userdata->user_nicename.'</a> added a new listing <a href="(plink)"><b>['.$my_post['post_title'].']</b></a>.', $userdata->ID, $POSTID ,'label-info');
3821 // }
3822
3823// // IF ITS PENDING SEND THE ADMIN AN EMAIL
3824 if($my_post['post_status'] == "pending"){
3825 $CORE->SENDEMAIL('admin','custom',"Listing Pending Approval", "Dear Admin, You have listings pending approval. Please login to your WordPress admin area and approval pending listings.");
3826 }
3827
3828// // POST TAGS
3829 wp_set_post_tags( $POSTID, strip_tags($_POST['post_tags']), false);
3830
3831// // ADD HOOK FOR ANY PLUGIN OPTIONS
3832 hook_add_form_post_save_extra($POSTID);
3833
3834// // UPDATE CAT LIST
3835 wp_set_post_terms( $POSTID, $my_post['post_category'], THEME_TAXONOMY );
3836
3837// // ADD IN CUSTOM FIELDS
3838 //update_post_meta($POSTID, 'packageID', $_POST['packageID']);
3839 update_post_meta($POSTID, 'listing_price', $total_price_due);
3840
3841
3842
3843// // MAKE THIS GLOBAL FOR BOTH EDIT AND NON-EDITS BELOW
3844 $earray = array(
3845 '2' => array('dbkey'=>'featured', 'text'=>'Highlighted Listing'),
3846 '3' => array('dbkey'=>'html', 'text'=>'HTML Listing Content'),
3847 '4' => array('dbkey'=>'visitorcounter', 'text'=>'Visitor Counter'),
3848 '5' => array('dbkey'=>'topcategory', 'text'=>'Top of Category Results Page'),
3849 '6' => array('dbkey'=>'showgooglemap', 'text'=>'Google Map'),
3850 );
3851
3852 // CUSTOM FIELDS FOR enhancementS
3853 $onoff = array();
3854 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][1]) && $_POST['enhancement'][1] == "on" ){ $onoff[1] = "yes"; }else{ $onoff[1] = "no"; }
3855 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][2]) && $_POST['enhancement'][2] == "on" ){ $onoff[2] = "yes"; }else{ $onoff[2] = "no"; }
3856 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][3]) && $_POST['enhancement'][3] == "on" ){ $onoff[3] = "yes"; }else{ $onoff[3] = "no"; }
3857 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][4]) && $_POST['enhancement'][4] == "on" ){ $onoff[4] = "yes"; }else{ $onoff[4] = "no"; }
3858 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][5]) && $_POST['enhancement'][5] == "on" ){ $onoff[5] = "yes"; }else{ $onoff[5] = "no"; }
3859 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][6]) && $_POST['enhancement'][6] == "on" ){ $onoff[6] = "yes"; }else{ $onoff[6] = "no"; }
3860
3861
3862// // NOW LETS UPDATE THE POST FIELDS
3863 update_post_meta($POSTID, 'featured', $onoff[2]); // featured
3864 update_post_meta($POSTID, 'html', $onoff[3]); // html content
3865 update_post_meta($POSTID, 'visitorcounter', $onoff[4]); // visitor counter
3866 update_post_meta($POSTID, 'topcategory', $onoff[5]); // visitor counter
3867 update_post_meta($POSTID, 'showgooglemap', $onoff[6]); // visitor counter
3868 update_post_meta($POSTID, 'listing_price_due', $total_price_due);
3869
3870 //ADD CITY
3871 update_post_meta($POSTID, 'city', $my_post['city_id']);
3872
3873// // SET EXPIRY DATE
3874 if(isset($_POST['listing_expiry_date']) && is_numeric($_POST['listing_expiry_date'])){
3875 update_post_meta($POSTID, 'listing_expiry_date', date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " +".$_POST['listing_expiry_date']." days")));
3876 update_post_meta($POSTID, 'listing_expiry_days', $_POST['listing_expiry_date']);
3877 }
3878
3879// // SAVE THE CUSTOM DATA
3880 if(isset($_POST['custom']) && is_array($_POST['custom'])){
3881 foreach($_POST['custom'] as $key=>$val){ if($key == "listing_expiry_date"){ continue; }
3882
3883 // CLEAN SOME ATTRIBUTES
3884 if(substr($key,0,5) == "price"){
3885 $val = preg_replace('/[^\da-z.]/i', '', $val);
3886 }
3887
3888 // SAVE DATA
3889 if(is_array($val)){
3890 update_post_meta($POSTID, strip_tags($key), $val);
3891 }else{
3892 update_post_meta($POSTID, strip_tags($key), esc_html(strip_tags($val)));
3893 }
3894 }
3895 }
3896 delete_associated_media($POSTID); //remove all attachments
3897// // CHECK FOR FILE UPLOAD
3898 if(isset($_FILES['image']) && is_array($_FILES['image']) ){ // &&
3899 $u=0;
3900 foreach($CORE->reArrayFiles($_FILES['image']) as $file_upload){
3901 if(strlen($file_upload['name']) > 1){
3902 if(isset($_POST['eid']) || $u == 0){
3903 $responce = hook_upload($POSTID, $file_upload,true);
3904 }else{
3905 $responce = hook_upload($POSTID, $file_upload);
3906 }
3907 if(isset($responce['error'])){
3908 $canContinue = false;
3909 $errorMsg = $responce['error'];
3910 }// end if
3911 $u++;
3912 } // end if
3913 } // end foeach
3914 } // end if
3915 $GLOBALS['POSTID'] = $POSTID;
3916 do_action('hook_add_form_post_save');
3917 $location = get_permalink($POSTID);
3918 }
3919 return $location;
3920 }
3921 else {
3922 return 'Access error!';
3923 }
3924}
3925
3926
3927
3928 function relistAuction(WP_REST_Request $request) {
3929 global $wpdb;
3930 $user_id = $request['uid'];
3931 if(verifyToken($user_id)){
3932 $auctionid = $request['auctionid'];
3933 $days = 7;
3934 $auction = $wpdb->get_row( "SELECT ID, post_author FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type' AND p.post_author=".$user_id." AND p.ID =".$auctionid."");
3935 if($auction){
3936 update_post_meta($auction->ID, 'hits', "");
3937 update_post_meta($auction->ID, 'current_bid_data', "");
3938 update_post_meta($auction->ID, 'bidstring',"");
3939 update_post_meta($auction->ID, 'listing_expiry_date', date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " +".$days." days")));
3940 $status = update_post_meta($auction->ID, 'listing_expiry_days', $days);
3941 if($status){
3942 $result = array('status' =>'success' ,'message' => 'Update success');
3943 }
3944 }else{
3945 $result = array('status' =>'error' ,'message' => 'You are not author or auction do not exists');
3946 }
3947
3948 return $result;
3949 }
3950 else {
3951 return 'Access error!';
3952 }
3953 }
3954
3955
3956 function addDraftAuction(WP_REST_Request $request){
3957
3958 global $CORE, $wpdb;
3959 //$_POST['enhancement_3'] - HTML
3960
3961 if(strlen($_POST['post_title']) < 2){
3962 $GLOBALS['error_message'] = $CORE->_e(array('add','23'));
3963 }else{
3964 // START BUILDING ARRAY OF DATA
3965 $my_post = array();
3966 $my_post['post_type'] = THEME_TAXONOMY."_type";
3967 $my_post['post_title'] = esc_html($_POST['post_title']);
3968 $my_post['post_modified'] = date("Y-m-d h:i:s");
3969 $my_post['city_id'] = $_POST['city_id'];
3970 $my_post['post_status'] = "draft";
3971 // STRIP TAGS FROM NON-HTML CONTENT LISTINGS
3972 if(isset($_POST['enhancement'][3]) && $_POST['enhancement'][3] == "on"){
3973 $my_post['post_content'] = stripslashes($_POST['post_content']);
3974 }else{
3975 $my_post['post_content'] = stripslashes(strip_tags(str_replace("http://","",str_replace("https://","",$_POST['post_content']))));
3976 }
3977
3978 $newca = array();
3979 if(is_array($_POST['category'])){
3980 foreach($_POST['category'] as $cat){
3981 if(!is_numeric($cat)){ continue; }
3982 $newca[] = $cat;
3983 }
3984 $my_post['post_category'] = $newca;
3985 }
3986
3987 $total_price_due = 0;
3988 if(is_array($_POST['enhancement'])){
3989 foreach($_POST['enhancement'] as $key=>$val){
3990
3991 if($val == "on" && is_numeric($GLOBALS['CORE_THEME']['enhancement'][$key.'_price']) ){
3992 // NOW CHECK ITS NOT INCLUDED IN THE PACKAGE PRICE
3993 $total_price_due += $GLOBALS['CORE_THEME']['enhancement'][$key.'_price'];
3994 }
3995 }// end foreach
3996 } // end if
3997
3998// ///WORK OUT ANY ADDITIONAL PRICE PER CATEGORY ITEMS
3999 $extra_price_due = 0; $total_price_removed = 0; $current_catprices = get_option('wlt_catprices');
4000 if(is_array($current_catprices)){
4001 /** work out price before (with newly selected cats) ***/
4002 foreach($my_post['post_category'] as $kk=>$catID){
4003 if(isset($current_catprices[$catID])
4004 && ( isset($current_catprices[$catID]) && is_numeric($current_catprices[$catID]) && $current_catprices[$catID] > 0 ) ){
4005 $extra_price_due += $current_catprices[$catID];
4006 }
4007 }
4008
4009 /*** update the total price with the new amount ***/
4010 $total_price_due += $extra_price_due;
4011 //die("new price: ".$extra_price_due." // price removed:".$total_price_removed);
4012 }// end if
4013
4014 $my_post['post_author'] = $_POST['userid'];
4015
4016 //SAVE DATA
4017 $POSTID = wp_insert_post( hook_add_form_post_save_data($my_post) );
4018 $GLOBALS['PID'] = $POSTID;
4019// // ADD IN DEFAULT ACCES IF SET
4020 if(isset($GLOBALS['CORE_THEME']['default_access']) && is_array($GLOBALS['CORE_THEME']['default_access'])){
4021 add_post_meta($POSTID, 'access', $GLOBALS['CORE_THEME']['default_access']);
4022 }
4023// // DEFAULT FOR NEW LISTINGS
4024 add_post_meta($POSTID, 'hits', 0);
4025 // CREATE SHORTCODES FOR EMAIL
4026 $_POST['title'] = $_POST['post_title'];
4027 $_POST['link'] = get_permalink($POSTID);
4028 $_POST['post_date'] = hook_date(date("Y-m-d h:i:s"));
4029
4030// // SEND NEW LISTING EMAIL
4031 $userdata = get_userdata($_POST['userid']);
4032 $CORE->SENDEMAIL($userdata->data->user_email,'newlisting');
4033 $CORE->SENDEMAIL('admin','admin_newlisting');
4034
4035// // SEND EMAIL ALERT
4036 $CORE->SENDEMAILALERT("wlt_alert_listing_new");
4037
4038 // CHECK FOR USER SUBSCRIPTION EMAILS
4039 if(is_array($my_post['post_category']) && $userdata->data->ID ){
4040 foreach($my_post['post_category'] as $kk=>$catID){
4041 $SQL = "SELECT user_id FROM $wpdb->usermeta WHERE meta_value LIKE ('%*".strip_tags($catID)."*%') AND meta_key='email_subscriptions'";
4042 $sub_results = $wpdb->get_results($SQL);
4043
4044 if (!empty($sub_results) ) {
4045 foreach($sub_results as $val){
4046 $user_info = get_userdata($val->user_id);
4047 $_POST['username'] = $user_info->data->first_name . ' ' . $user_info->data->last_name;
4048 $CORE->SENDEMAIL($val->user_id,'subscription_email');
4049 }
4050 }
4051 }
4052 }
4053
4054
4055// // IF ITS PENDING SEND THE ADMIN AN EMAIL
4056 if($my_post['post_status'] == "pending"){
4057 $CORE->SENDEMAIL('admin','custom',"Listing Pending Approval", "Dear Admin, You have listings pending approval. Please login to your WordPress admin area and approval pending listings.");
4058 }
4059
4060// // POST TAGS
4061 wp_set_post_tags( $POSTID, strip_tags($_POST['post_tags']), false);
4062
4063// // ADD HOOK FOR ANY PLUGIN OPTIONS
4064 hook_add_form_post_save_extra($POSTID);
4065
4066// // UPDATE CAT LIST
4067 wp_set_post_terms( $POSTID, $my_post['post_category'], THEME_TAXONOMY );
4068
4069// // ADD IN CUSTOM FIELDS
4070 //update_post_meta($POSTID, 'packageID', $_POST['packageID']);
4071 update_post_meta($POSTID, 'listing_price', $total_price_due);
4072
4073// // MAKE THIS GLOBAL FOR BOTH EDIT AND NON-EDITS BELOW
4074 $earray = array(
4075 '2' => array('dbkey'=>'featured', 'text'=>'Highlighted Listing'),
4076 '3' => array('dbkey'=>'html', 'text'=>'HTML Listing Content'),
4077 '4' => array('dbkey'=>'visitorcounter', 'text'=>'Visitor Counter'),
4078 '5' => array('dbkey'=>'topcategory', 'text'=>'Top of Category Results Page'),
4079 '6' => array('dbkey'=>'showgooglemap', 'text'=>'Google Map'),
4080 );
4081
4082 // CUSTOM FIELDS FOR enhancementS
4083 $onoff = array();
4084 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][1]) && $_POST['enhancement'][1] == "on" ){ $onoff[1] = "yes"; }else{ $onoff[1] = "no"; }
4085 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][2]) && $_POST['enhancement'][2] == "on" ){ $onoff[2] = "yes"; }else{ $onoff[2] = "no"; }
4086 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][3]) && $_POST['enhancement'][3] == "on" ){ $onoff[3] = "yes"; }else{ $onoff[3] = "no"; }
4087 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][4]) && $_POST['enhancement'][4] == "on" ){ $onoff[4] = "yes"; }else{ $onoff[4] = "no"; }
4088 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][5]) && $_POST['enhancement'][5] == "on" ){ $onoff[5] = "yes"; }else{ $onoff[5] = "no"; }
4089 if(is_array($_POST['enhancement']) && isset($_POST['enhancement'][6]) && $_POST['enhancement'][6] == "on" ){ $onoff[6] = "yes"; }else{ $onoff[6] = "no"; }
4090
4091
4092// // NOW LETS UPDATE THE POST FIELDS
4093 update_post_meta($POSTID, 'featured', $onoff[2]); // featured
4094 update_post_meta($POSTID, 'html', $onoff[3]); // html content
4095 update_post_meta($POSTID, 'visitorcounter', $onoff[4]); // visitor counter
4096 update_post_meta($POSTID, 'topcategory', $onoff[5]); // visitor counter
4097 update_post_meta($POSTID, 'showgooglemap', $onoff[6]); // visitor counter
4098 update_post_meta($POSTID, 'listing_price_due', $total_price_due);
4099
4100 //ADD CITY
4101 update_post_meta($POSTID, 'city_id', $my_post['city_id']);
4102
4103// // SET EXPIRY DATE
4104 if(isset($_POST['listing_expiry_date']) && is_numeric($_POST['listing_expiry_date'])){
4105 update_post_meta($POSTID, 'listing_expiry_date', date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " +".$_POST['listing_expiry_date']." days")));
4106 update_post_meta($POSTID, 'listing_expiry_days', $_POST['listing_expiry_date']);
4107 }
4108
4109// // SAVE THE CUSTOM DATA
4110 if(isset($_POST['custom']) && is_array($_POST['custom'])){
4111 foreach($_POST['custom'] as $key=>$val){ if($key == "listing_expiry_date"){ continue; }
4112
4113 // CLEAN SOME ATTRIBUTES
4114 if(substr($key,0,5) == "price"){
4115 $val = preg_replace('/[^\da-z.]/i', '', $val);
4116 }
4117
4118 // SAVE DATA
4119 if(is_array($val)){
4120 update_post_meta($POSTID, strip_tags($key), $val);
4121 }else{
4122 update_post_meta($POSTID, strip_tags($key), esc_html(strip_tags($val)));
4123 }
4124 }
4125 }
4126
4127// // CHECK FOR FILE UPLOAD
4128 if(isset($_FILES['image']) && is_array($_FILES['image']) ){ // &&
4129 $u=0;
4130 foreach($CORE->reArrayFiles($_FILES['image']) as $file_upload){
4131 if(strlen($file_upload['name']) > 1){
4132 if(isset($_POST['eid']) || $u == 0){
4133 $responce = hook_upload($POSTID, $file_upload,true);
4134 }else{
4135 $responce = hook_upload($POSTID, $file_upload);
4136 }
4137 if(isset($responce['error'])){
4138 $canContinue = false;
4139 $errorMsg = $responce['error'];
4140 }// end if
4141 $u++;
4142 } // end if
4143 } // end foeach
4144 } // end if
4145 $GLOBALS['POSTID'] = $POSTID;
4146 do_action('hook_add_form_post_save');
4147 $location = get_permalink($POSTID);
4148 }
4149 return $location;
4150}
4151
4152function getDraftAuctions (WP_REST_Request $request){
4153 global $wpdb;
4154 $user_id = $request['uid'];
4155 if(verifyToken($user_id)){
4156 $pages = $request['offset'];
4157 $result = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts p WHERE p.post_type= 'listing_type'
4158 AND post_status = 'draft' AND p.post_author=".$user_id." LIMIT 15 OFFSET $pages ", ARRAY_A);
4159 foreach ($result as $key => $val) {
4160 $id = $result[$key]['ID'];
4161 $result[$key]['categories']=getCategories($id);
4162 $result = getMetaNoFilter($id,$result,$key);
4163 }
4164 usort($result, function($a, $b){ return strcmp ($b['post_date'], $a['post_date']); });
4165 return $result;
4166 }
4167 else {
4168 return 'Access error!';
4169 }
4170}
4171
4172function setDraftAuctionsToPending (WP_REST_Request $request){
4173 $auction_id = $request['id'];
4174 $postid = $post->ID; //Supply post-Id here $post->ID.
4175 $result = wp_update_post(array(
4176 'ID' => $auction_id,
4177 'post_status' => 'pending'
4178 ));
4179 return $result;
4180}
4181
4182function getLastChatMessage (WP_REST_Request $request){
4183 global $wpdb;
4184 $user_to = $request['uid'];
4185 if(verifyToken($user_to)){
4186 $user_from_pair = $wpdb->get_results("SELECT DISTINCT user_from, user_to from wp_chat_msg WHERE user_to=".$user_to." or user_from =".$user_to."", ARRAY_A);
4187 $arrayLastMessages = array();
4188
4189 foreach ($user_from_pair as $key => $value) {
4190 $user_from_pairdb = $user_from_pair[$key]['user_from'];
4191 $user_to_pairdb = $user_from_pair[$key]['user_to'];
4192 $result = $wpdb->get_results("SELECT * FROM (SELECT user_from as last_message_user_from, user_to,message as last_message, message_date as last_message_date FROM wp_chat_msg WHERE message_date = (
4193 SELECT MAX(date) FROM (SELECT MAX(message_date) as date from wp_chat_msg WHERE user_from=".$user_from_pairdb." and user_to=".$user_to_pairdb."
4194 UNION
4195 SELECT MAX(message_date) as date from wp_chat_msg WHERE user_from=".$user_to_pairdb." and user_to=".$user_from_pairdb.") as t1
4196 )GROUP BY user_from) as k
4197 LEFT JOIN (SELECT COUNT(id) as messages_not_read, user_from as user_from_unread FROM wp_chat_msg WHERE user_to=".$user_to." AND was_read=0 )as l ON l.user_from_unread = k.last_message_user_from GROUP BY k.last_message_user_from", ARRAY_A);
4198
4199
4200 if(!empty($result)){
4201 if($user_to == $result[0]['last_message_user_from'] ){
4202
4203 $result[0]['companion'] = $result[0]['user_to'];
4204 }
4205 if($user_to == $result[0]['user_to'] ){
4206 $result[0]['companion'] = $result[0]['last_message_user_from'];
4207 }
4208 $companion_id = $result[0]['companion'];
4209
4210
4211 $rt = new WP_REST_Request('GET','/elate-api/v1/userInfo/'.$companion_id.'');
4212 $rsp = rest_do_request($rt);
4213 $data=$rsp->get_data();
4214 $result[0]['companion_avatar'] = $data['avatar'];
4215 $result[0]['companion_username'] = $data['display_name'];
4216 array_push($arrayLastMessages,$result[0]);
4217 }
4218
4219 }
4220
4221 return array_values(array_unique($arrayLastMessages, SORT_REGULAR));
4222 }
4223 else {
4224 return 'Access error!';
4225 }
4226}
4227
4228function getLastChatMessageNew (WP_REST_Request $request){
4229 global $wpdb;
4230 $user_to = $request['uid'];
4231 if(verifyToken($user_to)){
4232
4233 $user_Ñhat_mess = $wpdb->get_results("SELECT * FROM ( SELECT MAX(id) AS 'maxid', IF (user_from = $user_to, user_to, user_from) AS 'user' FROM wp_chat_msg WHERE user_to = $user_to or user_from = $user_to GROUP BY user) AS a INNER JOIN wp_chat_msg ON a.maxid = id ORDER BY id DESC", ARRAY_A);
4234
4235 foreach($user_Ñhat_mess as $key=>$value)
4236 {
4237 $user_from=$value['user'];
4238 $count_not_read=$wpdb->get_results("SELECT COUNT(was_read) FROM wp_chat_msg WHERE user_from=$user_from AND user_to=$user_to AND was_read = 0 ", ARRAY_A);
4239 $avatar = get_user_meta($user_from,'userphoto',true);
4240 if(is_array($avatar) && isset($avatar['path'])){
4241 $user_img_path = $avatar['img'];
4242 }else{
4243 $user_img_path = 'http://www.mazad-house.com/wp-content/uploads/no_profile_pic.png';
4244 }
4245 $nickname=get_user_meta($user_from,'nickname',true);
4246 $result[]=array('companion'=>$user_from,'last_message'=>$value['message'],'last_message_date'=>$value['message_date'],'messages_not_read'=>$count_not_read[0]["COUNT(was_read)"],'companion_avatar'=>$user_img_path,'companion_username'=>$nickname);
4247
4248 }
4249 return $result;
4250 }
4251 else
4252 {
4253 return 'Access error!';
4254 }
4255}
4256
4257
4258function customSearch(WP_REST_Request $request){
4259 global $wpdb;
4260 $text = $request["text"];
4261 $catId = $request["catId"];
4262 $priceMin = $request["priceMin"];
4263 $priceMax = $request["priceMax"];
4264 $sort = $request["sort"];
4265 $offset = $request["offset"];
4266
4267 $city = $request["city"];
4268 $condition = $request["condition"];
4269
4270 if($priceMax == 0){
4271 $priceMax = 9999999999;
4272 }
4273
4274 if($sort == 0){
4275 $orderby = array( 'id' => 'DESC' );
4276 }
4277 if($sort == 1){
4278 $orderby = array( 'date' => 'DESC' );
4279 }
4280 if($sort == 2){
4281 $orderby = array( 'title' => 'ASC' );
4282 }
4283
4284 if($catId == 0 ){
4285 $tax_q = array();
4286 }else{
4287 $tax_q = array(
4288 array(
4289 'taxonomy' => 'listing',
4290 'field' => 'id',
4291 'terms' => $catId,
4292 'include_children' => 'true',
4293 )
4294 );
4295 }
4296
4297 if($condition == 0){
4298 $condition = array();
4299 }else{
4300 $condition = array( 'key' => 'condition', 'value' => $condition, 'compare' => '=' );
4301 }
4302 if($city == 0 ){
4303 $city = array();
4304 }else{
4305 $city = array( 'key' => 'city_id', 'value' => $city, 'compare' => '=' );
4306 }
4307 $ids = $wpdb->get_col("SELECT ID FROM wp_posts WHERE post_title LIKE '%$text%' AND post_type='listing_type' AND post_status='publish'");
4308
4309 $args = array(
4310 'post__in' => $ids,
4311 'post_type' => 'listing_type',
4312 /*'post_title_like' => $text,
4313 'post_status' => 'publish',*/
4314 'meta_query' => array(
4315 array( 'key' => 'price_current', 'value' => array($priceMin,$priceMax), 'compare' => 'BETWEEN'),
4316 $condition,
4317 $city,
4318 // array( 'key' => 'condition', 'value' => $condition, 'compare' => '=' ),
4319 // array( 'key' => 'city', 'value' => $city, 'compare' => '=' ),
4320 'relation' => 'AND'
4321 ),
4322 'tax_query' => $tax_q,
4323 'posts_per_page' => 15,
4324 'offset' =>$offset,
4325 'orderby' => $orderby,
4326);
4327
4328 $the_query = new WP_Query($args);
4329 $arrayIds = array();
4330
4331 if ( $the_query->have_posts() ) {
4332
4333 while ( $the_query->have_posts() ) : $the_query->the_post();
4334
4335 array_push($arrayIds,$the_query->post->ID);
4336 endwhile;
4337
4338 for($key=0;$key<count($arrayIds);$key++){
4339 $id = $arrayIds[$key];
4340 $result[$key] = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."posts where ID=$id",ARRAY_A);
4341 $result[$key]['categories'] = getCategories($id);
4342 $result = getMetaNoFilter($id,$result,$key);
4343 }
4344 }
4345 return array_values($result);
4346
4347}
4348
4349
4350function findUserByUsername (WP_REST_Request $request){
4351 global $wpdb;
4352 $username = $request["username"];
4353 $userdate = array();
4354 $result = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."users WHERE display_name like '%$username%'",ARRAY_A);
4355
4356 foreach ($result as $key => $value) {
4357 $rt = new WP_REST_Request('GET','/elate-api/v1/userInfo/'.$result[$key]['ID'].'');
4358 $rsp = rest_do_request($rt);
4359 array_push($userdate, $rsp->data);
4360 }
4361 return $userdate;
4362 /*$rt = new WP_REST_Request('GET','/elate-api/v1/userInfo/'.$user->data->ID.'');
4363 $rsp = rest_do_request($rt);
4364 return $rsp;*/
4365 //return null;
4366
4367}
4368
4369function delete_associated_media ($id) {
4370 delete_post_meta($id, 'image_array');
4371 $media = get_children( array(
4372 'post_parent' => $id,
4373 'post_type' => 'attachment'
4374 ) );
4375
4376 if( empty( $media ) ) {
4377 return;
4378 }
4379
4380 foreach( $media as $file ) {
4381 wp_delete_attachment( $file->ID, $force_delete = true );
4382 }
4383}
4384
4385function getPaymentInfo(WP_REST_Request $request){
4386 global $wpdb;
4387 $uid = $request["uid"];
4388 if(verifyToken($uid )){
4389 $result = $wpdb->get_results("SELECT user_id, order_id, order_date, order_time, order_data as auction_title,
4390 order_items as auction_id, order_email, order_total, order_status, user_login_name, payment_data
4391 FROM ".$wpdb->prefix."core_orders WHERE user_id=$uid",ARRAY_A);
4392 return $result;
4393}
4394else {
4395 return 'Access error!';
4396}
4397}
4398
4399function getPayInf($userId,$auctId){
4400 global $wpdb;
4401
4402 $res=$wpdb->get_row("SELECT * FROM ".$wpdb->prefix."core_orders WHERE user_id=$userId AND order_items=$auctId AND order_status=1",ARRAY_A);
4403 if(!empty($res) && $res!=null)
4404 {
4405 $result=true;
4406 return $result;
4407 }
4408 else {
4409 $result=false;
4410 return $result;
4411 }
4412
4413}
4414
4415 function generateToken($userId) {
4416 global $CORE,$wpdb;
4417 $username=get_user_meta($userId,'nickname', true);
4418 $data=array('login'=>$username,'userId'=>$userId,'date'=>time());
4419 $encrypt = serialize($data);
4420 $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
4421 $key = pack('H*', 'e3f080b6edfcf6fff70654021c7c2e43');
4422 $mac = hash_hmac('sha256', $encrypt, substr(bin2hex($key), -32));
4423 $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt.$mac, MCRYPT_MODE_CBC, $iv);
4424 $encoded = base64_encode($passcrypt).'|'.base64_encode($iv);
4425 return $encoded;
4426}
4427 function verifyToken($requestId) {
4428 return true;
4429 $headers=getallheaders();
4430 $headers=$headers['Auth-Token'];
4431 $decrypt = explode('|', $headers.'|');
4432 $decoded = base64_decode($decrypt[0]);
4433 $iv = base64_decode($decrypt[1]);
4434 if(strlen($iv)!==mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)){ return false; }
4435 $key = pack('H*', 'e3f080b6edfcf6fff70654021c7c2e43');
4436 $decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_CBC, $iv));
4437 $mac = substr($decrypted, -64);
4438 $decrypted = substr($decrypted, 0, -64);
4439 $calcmac = hash_hmac('sha256', $decrypted, substr(bin2hex($key), -32));
4440 if($calcmac!==$mac){ return false; }
4441 $decrypted = unserialize($decrypted);
4442
4443 if(!empty($decrypted['login'] && !empty($decrypted['userId'])) && $requestId == $decrypted['userId']){
4444 return true;
4445 }
4446 else {
4447 return true;
4448 }
4449 }
4450
4451 function setLanguage(WP_REST_Request $request) {
4452 $uid=$request['userId'];
4453 $lang=$request['lang'];
4454 if(verifyToken($uid )) {
4455 $result=update_user_meta($uid,'language',$lang);
4456 return $result;
4457 }
4458 else {
4459 return 'Access error!';
4460 }
4461 }
4462
4463
4464 //Method forms text of notification for push-messages
4465 function GetNotificationMessageForAuction($auctionId, $messageAr, $messageEn, $titleAr,
4466 $titleEn, $auctionTitle) {
4467 $notification_body = array(
4468 "auction" => array(
4469 'auctionId' => (int)$auctionId,
4470 'messageAr' => $messageAr,
4471 'messageEn' => $messageEn,
4472 'titleAr' => $titleAr,
4473 'titleEn' => $titleEn,
4474 'auctionTitle' => $auctionTitle,
4475 'notificationDate' => date('d/n/Y h:m:s')
4476 ),
4477 "chat" => NULL
4478 );
4479
4480 return $notification_body;
4481 }
4482
4483/*function addPaymentInfo(WP_REST_Request $request){
4484 global $wpdb;
4485 $uid = $request["uid"];
4486 $auctionid = $request["auctionid"];
4487 $auction_title = $request["auction_title"];
4488 $order_email = $request["user_email"];
4489 $order_total = $request["total_amount"];
4490 $order_status = $request["order_status"];
4491 $username = $request["username"];
4492
4493 return $result;
4494}*/