/
pwg.images.php
2710 lines (2334 loc) · 66 KB
/
pwg.images.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// +-----------------------------------------------------------------------+
// | This file is part of Piwigo. |
// | |
// | For copyright and license information, please view the COPYING.txt |
// | file that was distributed with this source code. |
// +-----------------------------------------------------------------------+
// +-----------------------------------------------------------------------+
// | UTILITIES |
// +-----------------------------------------------------------------------+
/**
* Sets associations of an image
* @param int $image_id
* @param string $categories_string - "cat_id[,rank];cat_id[,rank]"
* @param bool $replace_mode - removes old associations
*/
function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
{
// let's add links between the image and the categories
//
// $params['categories'] should look like 123,12;456,auto;789 which means:
//
// 1. associate with category 123 on rank 12
// 2. associate with category 456 on automatic rank
// 3. associate with category 789 on automatic rank
$cat_ids = array();
$rank_on_category = array();
$search_current_ranks = false;
$tokens = explode(';', $categories_string);
foreach ($tokens as $token)
{
@list($cat_id, $rank) = explode(',', $token);
if (!preg_match('/^\d+$/', $cat_id))
{
continue;
}
$cat_ids[] = $cat_id;
if (!isset($rank))
{
$rank = 'auto';
}
$rank_on_category[$cat_id] = $rank;
if ($rank == 'auto')
{
$search_current_ranks = true;
}
}
$cat_ids = array_unique($cat_ids);
if (count($cat_ids) == 0)
{
return new PwgError(500,
'[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
);
}
$query = '
SELECT id
FROM '.CATEGORIES_TABLE.'
WHERE id IN ('.implode(',', $cat_ids).')
;';
$db_cat_ids = query2array($query, null, 'id');
$unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
if (count($unknown_cat_ids) != 0)
{
return new PwgError(500,
'[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
);
}
$to_update_cat_ids = array();
// in case of replace mode, we first check the existing associations
$query = '
SELECT category_id
FROM '.IMAGE_CATEGORY_TABLE.'
WHERE image_id = '.$image_id.'
;';
$existing_cat_ids = query2array($query, null, 'category_id');
if ($replace_mode)
{
$to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
if (count($to_remove_cat_ids) > 0)
{
$query = '
DELETE
FROM '.IMAGE_CATEGORY_TABLE.'
WHERE image_id = '.$image_id.'
AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
;';
pwg_query($query);
update_category($to_remove_cat_ids);
}
}
$new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
if (count($new_cat_ids) == 0)
{
return true;
}
if ($search_current_ranks)
{
$query = '
SELECT category_id, MAX(`rank`) AS max_rank
FROM '.IMAGE_CATEGORY_TABLE.'
WHERE `rank` IS NOT NULL
AND category_id IN ('.implode(',', $new_cat_ids).')
GROUP BY category_id
;';
$current_rank_of = query2array(
$query,
'category_id',
'max_rank'
);
foreach ($new_cat_ids as $cat_id)
{
if (!isset($current_rank_of[$cat_id]))
{
$current_rank_of[$cat_id] = 0;
}
if ('auto' == $rank_on_category[$cat_id])
{
$rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
}
}
}
$inserts = array();
foreach ($new_cat_ids as $cat_id)
{
$inserts[] = array(
'image_id' => $image_id,
'category_id' => $cat_id,
'rank' => $rank_on_category[$cat_id],
);
}
mass_inserts(
IMAGE_CATEGORY_TABLE,
array_keys($inserts[0]),
$inserts
);
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
update_category($new_cat_ids);
}
/**
* Merge chunks added by pwg.images.addChunk
* @param string $output_filepath
* @param string $original_sum
* @param string $type
*/
function merge_chunks($output_filepath, $original_sum, $type)
{
global $conf, $logger;
$logger->debug('[merge_chunks] input parameter $output_filepath : '.$output_filepath, 'WS');
if (is_file($output_filepath))
{
unlink($output_filepath);
if (is_file($output_filepath))
{
return new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
}
}
$upload_dir = $conf['upload_dir'].'/buffer';
$pattern = '/'.$original_sum.'-'.$type.'/';
$chunks = array();
if ($handle = opendir($upload_dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match($pattern, $file))
{
$logger->debug($file, 'WS');
$chunks[] = $upload_dir.'/'.$file;
}
}
closedir($handle);
}
sort($chunks);
if (function_exists('memory_get_usage')) {
$logger->debug('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage(), 'WS');
}
$i = 0;
foreach ($chunks as $chunk)
{
$string = file_get_contents($chunk);
if (function_exists('memory_get_usage')) {
$logger->debug('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage(), 'WS');
}
if (!file_put_contents($output_filepath, $string, FILE_APPEND))
{
return new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
}
unlink($chunk);
}
if (function_exists('memory_get_usage')) {
$logger->debug('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage(), 'WS');
}
}
/**
* Deletes chunks added with pwg.images.addChunk
* @param string $original_sum
* @param string $type
*
* Function introduced for Piwigo 2.4 and the new "multiple size"
* (derivatives) feature. As we only need the biggest sent photo as
* "original", we remove chunks for smaller sizes. We can't make it earlier
* in ws_images_add_chunk because at this moment we don't know which $type
* will be the biggest (we could remove the thumb, but let's use the same
* algorithm)
*/
function remove_chunks($original_sum, $type)
{
global $conf;
$upload_dir = $conf['upload_dir'].'/buffer';
$pattern = '/'.$original_sum.'-'.$type.'/';
$chunks = array();
if ($handle = opendir($upload_dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match($pattern, $file))
{
$chunks[] = $upload_dir.'/'.$file;
}
}
closedir($handle);
}
foreach ($chunks as $chunk)
{
unlink($chunk);
}
}
// +-----------------------------------------------------------------------+
// | METHODS |
// +-----------------------------------------------------------------------+
/**
* API method
* Adds a comment to an image
* @param mixed[] $params
* @option int image_id
* @option string author
* @option string content
* @option string key
*/
function ws_images_addComment($params, $service)
{
$query = '
SELECT DISTINCT image_id
FROM '. IMAGE_CATEGORY_TABLE .'
INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
WHERE commentable="true"
AND image_id='.$params['image_id'].
get_sql_condition_FandF(
array(
'forbidden_categories' => 'id',
'visible_categories' => 'id',
'visible_images' => 'image_id'
),
' AND'
).'
;';
if (!pwg_db_num_rows(pwg_query($query)))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid image_id');
}
$comm = array(
'author' => trim($params['author']),
'content' => trim($params['content']),
'image_id' => $params['image_id'],
);
include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
$comment_action = insert_user_comment($comm, $params['key'], $infos);
switch ($comment_action)
{
case 'reject':
$infos[] = l10n('Your comment has NOT been registered because it did not pass the validation rules');
return new PwgError(403, implode("; ", $infos) );
case 'validate':
case 'moderate':
$ret = array(
'id' => $comm['id'],
'validation' => $comment_action=='validate',
);
return array('comment' => new PwgNamedStruct($ret));
default:
return new PwgError(500, "Unknown comment action ".$comment_action );
}
}
/**
* API method
* Returns detailed information for an element
* @param mixed[] $params
* @option int image_id
* @option int comments_page
* @option int comments_per_page
*/
function ws_images_getInfo($params, $service)
{
global $user, $conf;
$query='
SELECT *
FROM '. IMAGES_TABLE .'
WHERE id='. $params['image_id'] .
get_sql_condition_FandF(
array('visible_images' => 'id'),
' AND'
).'
LIMIT 1
;';
$result = pwg_query($query);
if (pwg_db_num_rows($result) == 0)
{
return new PwgError(404, 'image_id not found');
}
$image_row = pwg_db_fetch_assoc($result);
$image_row = array_merge($image_row, ws_std_get_urls($image_row));
//-------------------------------------------------------- related categories
$query = '
SELECT id, name, permalink, uppercats, global_rank, commentable
FROM '. IMAGE_CATEGORY_TABLE .'
INNER JOIN '. CATEGORIES_TABLE .' ON category_id = id
WHERE image_id = '. $image_row['id'] .
get_sql_condition_FandF(
array('forbidden_categories' => 'category_id'),
' AND'
).'
;';
$result = pwg_query($query);
$is_commentable = false;
$related_categories = array();
while ($row = pwg_db_fetch_assoc($result))
{
if ($row['commentable']=='true')
{
$is_commentable = true;
}
unset($row['commentable']);
$row['url'] = make_index_url(
array(
'category' => $row
)
);
$row['page_url'] = make_picture_url(
array(
'image_id' => $image_row['id'],
'image_file' => $image_row['file'],
'category' => $row
)
);
$row['id']=(int)$row['id'];
$related_categories[] = $row;
}
usort($related_categories, 'global_rank_compare');
if (empty($related_categories) and !is_admin())
{
// photo might be in the lounge? or simply orphan. A standard user should not get
// info. An admin should still be able to get info.
return new PwgError(401, 'Access denied');
}
//-------------------------------------------------------------- related tags
$related_tags = get_common_tags(array($image_row['id']), -1);
foreach ($related_tags as $i=>$tag)
{
$tag['url'] = make_index_url(
array(
'tags' => array($tag)
)
);
$tag['page_url'] = make_picture_url(
array(
'image_id' => $image_row['id'],
'image_file' => $image_row['file'],
'tags' => array($tag),
)
);
unset($tag['counter']);
$tag['id'] = (int)$tag['id'];
$related_tags[$i] = $tag;
}
//------------------------------------------------------------- related rates
$rating = array(
'score' => $image_row['rating_score'],
'count' => 0,
'average' => null,
);
if (isset($rating['score']))
{
$query = '
SELECT COUNT(rate) AS count, ROUND(AVG(rate),2) AS average
FROM '. RATE_TABLE .'
WHERE element_id = '. $image_row['id'] .'
;';
$row = pwg_db_fetch_assoc(pwg_query($query));
$rating['score'] = (float)$rating['score'];
$rating['average'] = (float)$row['average'];
$rating['count'] = (int)$row['count'];
}
//---------------------------------------------------------- related comments
$related_comments = array();
$where_comments = 'image_id = '.$image_row['id'];
if (!is_admin())
{
$where_comments .= ' AND validated="true"';
}
$query = '
SELECT COUNT(id) AS nb_comments
FROM '. COMMENTS_TABLE .'
WHERE '. $where_comments .'
;';
list($nb_comments) = query2array($query, null, 'nb_comments');
$nb_comments = (int)$nb_comments;
if ($nb_comments>0 and $params['comments_per_page']>0)
{
$query = '
SELECT id, date, author, content
FROM '. COMMENTS_TABLE .'
WHERE '. $where_comments .'
ORDER BY date
LIMIT '. (int)$params['comments_per_page'] .'
OFFSET '. (int)($params['comments_per_page']*$params['comments_page']) .'
;';
$result = pwg_query($query);
while ($row = pwg_db_fetch_assoc($result))
{
$row['id'] = (int)$row['id'];
$related_comments[] = $row;
}
}
$comment_post_data = null;
if ($is_commentable and
(!is_a_guest()
or (is_a_guest() and $conf['comments_forall'] )
)
)
{
$comment_post_data['author'] = stripslashes($user['username']);
$comment_post_data['key'] = get_ephemeral_key(2, $params['image_id']);
}
$ret = $image_row;
foreach (array('id','width','height','hit','filesize') as $k)
{
if (isset($ret[$k]))
{
$ret[$k] = (int)$ret[$k];
}
}
foreach (array('path', 'storage_category_id') as $k)
{
unset($ret[$k]);
}
$ret['rates'] = array(
WS_XML_ATTRIBUTES => $rating
);
$ret['categories'] = new PwgNamedArray(
$related_categories,
'category',
array('id','url', 'page_url')
);
$ret['tags'] = new PwgNamedArray(
$related_tags,
'tag',
ws_std_get_tag_xml_attributes()
);
if (isset($comment_post_data))
{
$ret['comment_post'] = array(
WS_XML_ATTRIBUTES => $comment_post_data
);
}
$ret['comments_paging'] = new PwgNamedStruct(
array(
'page' => $params['comments_page'],
'per_page' => $params['comments_per_page'],
'count' => count($related_comments),
'total_count' => $nb_comments,
)
);
$ret['comments'] = new PwgNamedArray(
$related_comments,
'comment',
array('id','date')
);
if ($service->_responseFormat != 'rest')
{
return $ret; // for backward compatibility only
}
else
{
return array(
'image' => new PwgNamedStruct($ret, null, array('name','comment'))
);
}
}
/**
* API method
* Rates an image
* @param mixed[] $params
* @option int image_id
* @option float rate
*/
function ws_images_rate($params, $service)
{
$query = '
SELECT DISTINCT id
FROM '. IMAGES_TABLE .'
INNER JOIN '. IMAGE_CATEGORY_TABLE .' ON id=image_id
WHERE id='. $params['image_id']
.get_sql_condition_FandF(
array(
'forbidden_categories' => 'category_id',
'forbidden_images' => 'id',
),
' AND'
).'
LIMIT 1
;';
if (pwg_db_num_rows(pwg_query($query))==0)
{
return new PwgError(404, 'Invalid image_id or access denied');
}
include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
$res = rate_picture($params['image_id'], (int)$params['rate']);
if ($res==false)
{
global $conf;
return new PwgError(403, 'Forbidden or rate not in '. implode(',', $conf['rate_items']));
}
return $res;
}
/**
* API method
* Returns a list of elements corresponding to a query search
* @param mixed[] $params
* @option string query
* @option int per_page
* @option int page
* @option string order (optional)
*/
function ws_images_search($params, $service)
{
include_once(PHPWG_ROOT_PATH .'include/functions_search.inc.php');
$images = array();
$where_clauses = ws_std_image_sql_filter($params, 'i.');
$order_by = ws_std_image_sql_order($params, 'i.');
$super_order_by = false;
if (!empty($order_by))
{
global $conf;
$conf['order_by'] = 'ORDER BY '.$order_by;
$super_order_by = true; // quick_search_result might be faster
}
$search_result = get_quick_search_results(
$params['query'],
array(
'super_order_by' => $super_order_by,
'images_where' => implode(' AND ', $where_clauses)
)
);
$image_ids = array_slice(
$search_result['items'],
$params['page']*$params['per_page'],
$params['per_page']
);
if (count($image_ids))
{
$query = '
SELECT *
FROM '. IMAGES_TABLE .'
WHERE id IN ('. implode(',', $image_ids) .')
;';
$result = pwg_query($query);
$image_ids = array_flip($image_ids);
$favorite_ids = get_user_favorites();
while ($row = pwg_db_fetch_assoc($result))
{
$image = array();
$image['is_favorite'] = isset($favorite_ids[ $row['id'] ]);
foreach (array('id', 'width', 'height', 'hit') as $k)
{
if (isset($row[$k]))
{
$image[$k] = (int)$row[$k];
}
}
foreach (array('file', 'name', 'comment', 'date_creation', 'date_available') as $k)
{
$image[$k] = $row[$k];
}
$image = array_merge($image, ws_std_get_urls($row));
$images[ $image_ids[ $image['id'] ] ] = $image;
}
ksort($images, SORT_NUMERIC);
$images = array_values($images);
}
return array (
'paging' => new PwgNamedStruct(
array(
'page' => $params['page'],
'per_page' => $params['per_page'],
'count' => count($images),
'total_count' => count($search_result['items']),
)
),
'images' => new PwgNamedArray(
$images,
'image',
ws_std_get_image_xml_attributes()
)
);
}
/**
* API method
* Registers a new search
* @param mixed[] $params
* @option string query
*/
function ws_images_filteredSearch_create($params, $service)
{
global $user;
include_once(PHPWG_ROOT_PATH.'include/functions_search.inc.php');
// * check the search exists
if (isset($params['search_id']))
{
if (empty(get_search_id_pattern($params['search_id'])))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid search_id input parameter.');
}
$search_info = get_search_info($params['search_id']);
if (empty($search_info))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'This search does not exist.');
}
}
$search = array('mode' => 'AND');
// * check all parameters
if (isset($params['allwords']))
{
$search['fields']['allwords'] = array();
if (!isset($params['allwords_mode']))
{
$params['allwords_mode'] = 'AND';
}
if (!preg_match('/^(OR|AND)$/', $params['allwords_mode']))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter allwords_mode');
}
$search['fields']['allwords']['mode'] = $params['allwords_mode'];
$allwords_fields_available = array('name', 'comment', 'file', 'author', 'tags', 'cat-title', 'cat-desc');
if (!isset($params['allwords_fields']))
{
$params['allwords_fields'] = $allwords_fields_available;
}
foreach ($params['allwords_fields'] as $field)
{
if (!in_array($field, $allwords_fields_available))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter allwords_fields');
}
}
$search['fields']['allwords']['fields'] = $params['allwords_fields'];
$search['fields']['allwords']['words'] = split_allwords($params['allwords']);
}
if (isset($params['tags']))
{
foreach ($params['tags'] as $tag_id)
{
if (!preg_match('/^\d+$/', $tag_id))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter tags');
}
}
if (!isset($params['tags_mode']))
{
$params['tags_mode'] = 'AND';
}
if (!preg_match('/^(OR|AND)$/', $params['tags_mode']))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter tags_mode');
}
$search['fields']['tags'] = array(
'words' => $params['tags'],
'mode' => $params['tags_mode'],
);
}
if (isset($params['categories']))
{
foreach ($params['categories'] as $cat_id)
{
if (!preg_match('/^\d+$/', $cat_id))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter categories');
}
}
$search['fields']['cat'] = array(
'words' => $params['categories'],
'sub_inc' => $params['categories_withsubs'] ?? false,
);
}
if (isset($params['authors']))
{
$authors = array();
foreach ($params['authors'] as $author)
{
$authors[] = strip_tags($author);
}
$search['fields']['author'] = array(
'words' => $authors,
'mode' => 'OR',
);
}
if (isset($params['filetypes']))
{
foreach ($params['filetypes'] as $ext)
{
if (!preg_match('/^[a-z0-9]+$/i', $ext))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter filetypes');
}
}
$search['fields']['filetypes'] = $params['filetypes'];
}
if (isset($params['added_by']))
{
foreach ($params['added_by'] as $user_id)
{
if (!preg_match('/^\d+$/', $user_id))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter added_by');
}
}
$search['fields']['added_by'] = $params['added_by'];
}
if (isset($params['date_posted']))
{
if (!preg_match('/^(24h|7d|30d|3m|6m|y\d+|)$/', $params['date_posted']))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid parameter date_posted');
}
$search['fields']['date_posted'] = $params['date_posted'];
}
list($search_uuid, $search_url) = save_search($search, $search_info['id'] ?? null);
return array(
'search_id' => $search_uuid,
'search_url' => $search_url,
);
}
/**
* API method
* Sets the level of an image
* @param mixed[] $params
* @option int image_id
* @option int level
*/
function ws_images_setPrivacyLevel($params, $service)
{
global $conf;
if (!in_array($params['level'], $conf['available_permission_levels']))
{
return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid level');
}
$query = '
UPDATE '. IMAGES_TABLE .'
SET level='. (int)$params['level'] .'
WHERE id IN ('. implode(',',$params['image_id']) .')
;';
$result = pwg_query($query);
pwg_activity('photo', $params['image_id'], 'edit');
$affected_rows = pwg_db_changes($result);
if ($affected_rows)
{
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
invalidate_user_cache();
}
return $affected_rows;
}
/**
* API method
* Sets the rank of an image in a category
* @param mixed[] $params
* @option int image_id
* @option int category_id
* @option int rank
*/
function ws_images_setRank($params, $service)
{
if (count($params['image_id']) > 1)
{
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
save_images_order(
$params['category_id'],
$params['image_id']
);
$query = '
SELECT
image_id
FROM '.IMAGE_CATEGORY_TABLE.'
WHERE category_id = '.$params['category_id'].'
ORDER BY `rank` ASC
;';
$image_ids = query2array($query, null, 'image_id');
// return data for client
return array(
'image_id' => $image_ids,
'category_id' => $params['category_id'],
);
}
// turns image_id into a simple int instead of array
$params['image_id'] = array_shift($params['image_id']);
if (empty($params['rank']))
{
return new PwgError(WS_ERR_MISSING_PARAM, 'rank is missing');
}
// does the image really exist?
$query = '
SELECT COUNT(*)
FROM '. IMAGES_TABLE .'
WHERE id = '. $params['image_id'] .'
;';
list($count) = pwg_db_fetch_row(pwg_query($query));
if ($count == 0)
{
return new PwgError(404, 'image_id not found');
}
// is the image associated to this category?
$query = '
SELECT COUNT(*)
FROM '. IMAGE_CATEGORY_TABLE .'
WHERE image_id = '. $params['image_id'] .'
AND category_id = '. $params['category_id'] .'
;';
list($count) = pwg_db_fetch_row(pwg_query($query));
if ($count == 0)
{
return new PwgError(404, 'This image is not associated to this category');
}
// what is the current higher rank for this category?
$query = '
SELECT MAX(`rank`) AS max_rank
FROM '. IMAGE_CATEGORY_TABLE .'
WHERE category_id = '. $params['category_id'] .'
;';
$row = pwg_db_fetch_assoc(pwg_query($query));
if (is_numeric($row['max_rank']))
{
if ($params['rank'] > $row['max_rank'])
{
$params['rank'] = $row['max_rank'] + 1;
}
}
else
{
$params['rank'] = 1;
}
// update rank for all other photos in the same category
$query = '
UPDATE '. IMAGE_CATEGORY_TABLE .'
SET `rank` = `rank` + 1
WHERE category_id = '. $params['category_id'] .'
AND `rank` IS NOT NULL
AND `rank` >= '. $params['rank'] .'
;';
pwg_query($query);
// set the new rank for the photo
$query = '
UPDATE '. IMAGE_CATEGORY_TABLE .'
SET `rank` = '. $params['rank'] .'
WHERE image_id = '. $params['image_id'] .'
AND category_id = '. $params['category_id'] .'
;';
pwg_query($query);
// return data for client
return array(
'image_id' => $params['image_id'],
'category_id' => $params['category_id'],
'rank' => $params['rank'],
);
}