]> git.bts.cx Git - cx.git/blob - cx/lib/images.php
correctly mark feed as atom
[cx.git] / cx / lib / images.php
1 <?php
2
3 cx_require('lib', 'db.php');
4 cx_require('lib', 'setup.php');
5 cx_require('lib', 'user_data.php');
6
7
8 class Image {
9 public $id;
10 public $uid;
11 public $alt_text;
12 public $url;
13
14 public function __construct($dict) {
15 $this->id = $dict['image_id']; // FIXME, hide when not used?
16 $this->uid = $dict['image_uid'];
17 $this->alt_text = $dict['image_alt_text'];
18 $this->url = $this->uid . '.' . $dict['image_type'];
19 }
20 }
21
22 function cx_images_add_image($site_id, $alt_text, $image_path, $image_original_filename) {
23 $path_parts = pathinfo($image_original_filename);
24
25 $uid = hash_file("sha256", $image_path);
26
27 $target_name = $uid . "." . $path_parts['extension'];
28 $path = cx_user_data_path('images', $target_name);
29
30 move_uploaded_file($image_path, $path);
31
32 $creation_time = $update_time = time();
33
34 $sql = 'INSERT INTO images (
35 image_site_id,
36 image_creation_time,
37 image_update_time,
38 image_uid,
39 image_type,
40 image_alt_text)
41 VALUES (?, ?, ?, ?, ?, ?);';
42 cx_db_exec($sql, $site_id, $creation_time, $update_time, $uid, $path_parts['extension'], $alt_text);
43 }
44
45 function cx_images_get(int $limit = 0) {
46 $sql = 'SELECT
47 image_id,
48 image_uid,
49 image_type,
50 image_alt_text
51 FROM images
52 ORDER BY image_creation_time DESC';
53
54 if ($limit > 0) {
55 $sql .= ' LIMIT ' . $limit;
56 }
57
58 $sql .= ';';
59
60 foreach (cx_db_query($sql) as $image) {
61 $i = new Image($image);
62 yield $i;
63 }
64 }
65
66 function cx_images_find_image($image_id) {
67 $sql = 'SELECT
68 image_id,
69 image_uid,
70 image_type,
71 image_alt_text
72 FROM images
73 WHERE image_id == ?
74 OR image_uid LIKE ?
75 LIMIT 1;';
76
77 foreach (cx_db_query($sql, $image_id, $image_id . "%") as $image) {
78 $i = new Image($image);
79 return $i;
80 }
81
82 return null;
83 }
84
85 cx_setup_register(1, function() {
86 cx_db_exec('CREATE TABLE images (
87 image_id INTEGER PRIMARY KEY,
88 image_site_id INTEGER,
89 image_creation_time INTEGER,
90 image_update_time INTEGER,
91 image_uid STRING,
92 image_type STRING,
93 image_alt_text STRING,
94
95 FOREIGN KEY(image_site_id) REFERENCES sites(site_id)
96 );');
97
98 mkdir(cx_user_data_path('images'), recursive: true);
99 });