issue: require message contents
[minimedit.git] / upload.inc.php
1 <?php
2 global $journalcol;
3 $journalcol = [
4         'assign' => 'Toegewezen aan',
5         'subject' => 'Onderwerp',
6 ];
7
8 function userupload($input, $target = NULL, $filename = NULL)
9 {
10         switch ($input['error']) {
11         case UPLOAD_ERR_OK:
12                 break;
13         case UPLOAD_ERR_INI_SIZE:
14         case UPLOAD_ERR_FORM_SIZE:
15                 throw new Exception('bestand te groot');
16                 break;
17         case UPLOAD_ERR_NO_FILE:
18                 return; # current
19         default:
20                 throw new Exception('bestand niet goed ontvangen: '.$input['error']);
21         }
22
23         if (isset($target)) {
24                 if (!file_exists($target) and !@mkdir($target, 0777, TRUE)) {
25                         throw new Exception("bestand kon niet geplaatst worden in $target");
26                 }
27                 $target .= '/';
28         }
29         if (isset($filename)) {
30                 $target .= $filename;
31         }
32         else {
33                 $target .= $input['name'];
34         }
35
36         if (file_exists($target)) {
37                 throw new Exception("bestandsnaam al aanwezig op $target");
38         }
39         if (!@move_uploaded_file($input['tmp_name'], $target)) {
40                 throw new Exception("bestand kon niet worden opgeslagen in $target");
41         }
42
43         foreach (@glob('thumb/*/') as $thumbres) {
44                 # attempt to remove old derivations
45                 @unlink($thumbres . '/' . $target);
46         }
47         return $target;
48 }
49
50 function messagehtml($input)
51 {
52         # convert user textarea post to formatted html
53         global $User;
54         if (empty($input)) {
55                 return;
56         }
57         if ($User and $User->admin and preg_match('/\A<[a-z][^>]*>/', $input)) {
58                 return $input;  # allow html input as is if privileged
59         }
60         $markup = [
61                 '{&lt;((?:\w+:|/).+?)&gt;}'    => '<$1>',                # unescape link entities
62                 '{<(?:https?://)?([^>\s|]+)>}' => '<$1 $1>',             # unnamed link
63                 '{<([^>\s|]+)[\s|]([^>]+)>}'   => '<a href="$1">$2</a>', # hyperlink
64                 "/\r\n?/" => "\n",        # unix newlines
65                 "/  +\n/" => "<br />",    # trailing spaces for hard line break
66                 "/^[-*] (.*)$\n?/m"            => '<li>$1</li>',         # list item
67                 "/^(.+)$\n?/m"                 => "<p>$1</p>\n",         # paragraph
68                 "{^<p>(<li>.*</li>)(?:</p>\n)?}m" => "<ul>$1</ul>\n",    # list container
69                 '/_(?<!\w_)(.+?)_(?!\w)/'      => '<em>$1</em>',         # italic
70                 '/\*(?<!\w\*)(.+?)\*(?!\w)/'   => '<strong>$1</strong>', # bold
71                 '/~(?<!\w~)(.+?)~(?!\w)/'      => '<s>$1</s>',           # stricken
72                 '/`(?<!\w`)(.+?)`(?!\w)/'      => '<code>$1</code>',     # monospace
73         ];
74         return preg_replace(array_keys($markup), array_values($markup), htmlspecialchars($input));
75 }
76
77 function createcomment($input, &$Issue = NULL)
78 {
79         # insert user message as database issue/reply
80         global $User, $Db, $Page, $journalcol;
81
82         $reply = [];
83         if (isset($input['reply']) and $body = $input['reply']) {
84                 $reply['raw'] = $body;
85                 $reply['message'] = messagehtml($body);
86         }
87         if ($_FILES and !empty($_FILES['image'])) {
88                 $target = 'data/upload';
89                 if (!file_exists($target)) {
90                         throw new Exception("er is geen uploadmap aanwezig op $target");
91                 }
92                 $target .= '/' . $User->login;
93                 if ($result = userupload($_FILES['image'], $target)) {
94                         $reply['raw'] = $reply['raw'] ?? '';
95                         $reply['raw'] .= "/$result";
96                         $reply['message'] = $reply['message'] ?? '';
97                         if (preg_match('(^image/)', $_FILES['image']['type'])) {
98                                 $reply['message'] .= sprintf('<p><img src="/thumb/640x/%s" /></p>', $result);
99                         }
100                         else {
101                                 $reply['message'] .= sprintf('<p>Bijgevoegd bestand: <a href="/%s" />%s</a></p>',
102                                         $result, basename($result)
103                                 );
104                         }
105                 }
106         }
107         if (!$reply) {
108                 throw new Exception("lege inhoud");
109         }
110         if (isset($input['announce'])) {
111                 $reply['announced'] = !!$input['announce'];
112         }
113
114         if (isset($input['id'])) {
115                 $newcomment = $input['id'];
116                 $filter = ['id = ?', $newcomment];
117                 $oldcomment = $Db->query("SELECT * FROM comments WHERE $filter[0]", [$filter[1]])->fetch();
118                 if (empty($oldcomment)) {
119                         throw new Exception('Antwoord niet gevonden');
120                 }
121
122                 $reply += [
123                         'updated' => ['now()'],
124                 ];
125                 $query = $Db->set('comments', $reply, $filter);
126                 if (!$query->rowCount()) {
127                         throw new Exception('Fout bij aanpassen');
128                 }
129
130                 if ($updated = $query->fetch()) {
131                         foreach (array_keys(get_object_vars($updated)) as $col) {
132                                 if ($updated->$col === $oldcomment->$col) {
133                                         continue; # unaltered
134                                 }
135                                 $Db->set('journal', [
136                                         'comment_id' => $newcomment,
137                                         'property'   => 'col',
138                                         'col'        => $col,
139                                         'old_value'  => $oldcomment->$col,
140                                         'value'      => $updated->$col,
141                                 ]);
142                         }
143                 }
144         }
145         else {
146                 $reply += [
147                         'page'    => "{$Page->handler}/{$Issue->id}",
148                         'author'  => $User->login,
149                 ];
150                 $query = $Db->set('comments', $reply);
151                 if (!$query->rowCount()) {
152                         throw new Exception('Fout bij opslaan');
153                 }
154                 $newcomment = $Db->dbh->lastInsertId('comments_id_seq');
155         }
156
157         if (isset($Issue)) {
158                 $row = [];
159                 foreach (array_keys($journalcol) as $col) {
160                         if (!isset($input[$col])) continue;
161                         $row[$col] = $input[$col] ?: NULL;
162                 }
163                 if (isset($input['status'])) {
164                         $reset = !empty($input['status']);
165                         if (isset($Issue->closed) !== $reset) {
166                                 $row['closed'] = $reset ? ['now()'] : NULL;
167                         }
168                 }
169                 $derived = ['updated' => ['now()']];
170                 $filter = ['id = ?', $Issue->id];
171                 $subquery = $Db->set('issues', $row + $derived, $filter);
172
173                 if ($updated = $subquery->fetch()) {
174                         foreach (array_keys($row) as $col) {
175                                 if ($updated->$col === $Issue->$col) {
176                                         continue; # unaltered
177                                 }
178                                 $Db->set('journal', [
179                                         'comment_id' => $newcomment,
180                                         'property'   => 'attr',
181                                         'col'        => $col,
182                                         'old_value'  => $Issue->$col,
183                                         'value'      => $updated->$col,
184                                 ]);
185                         }
186                         $Issue = $updated;
187                 }
188         }
189
190         return $newcomment;
191 }