]> git.mxchange.org Git - friendica.git/blob - src/Model/FileTag.php
Merge pull request #8265 from nupplaphil/task/add_license
[friendica.git] / src / Model / FileTag.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Database\DBA;
25 use Friendica\DI;
26
27 /**
28  * This class handles FileTag related functions
29  *
30  * post categories and "save to file" use the same item.file table for storage.
31  * We will differentiate the different uses by wrapping categories in angle brackets
32  * and save to file categories in square brackets.
33  * To do this we need to escape these characters if they appear in our tag.
34  */
35 class FileTag
36 {
37         /**
38          * URL encode <, >, left and right brackets
39          *
40          * @param string $s String to be URL encoded.
41          *
42          * @return string   The URL encoded string.
43          */
44         public static function encode($s)
45         {
46                 return str_replace(['<', '>', '[', ']'], ['%3c', '%3e', '%5b', '%5d'], $s);
47         }
48
49         /**
50          * URL decode <, >, left and right brackets
51          *
52          * @param string $s The URL encoded string to be decoded
53          *
54          * @return string   The decoded string.
55          */
56         public static function decode($s)
57         {
58                 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
59         }
60
61         /**
62          * Query files for tag
63          *
64          * @param string $table The table to be queired.
65          * @param string $s     The search term
66          * @param string $type  Optional file type.
67          *
68          * @return string       Query string.
69          */
70         public static function fileQuery($table, $s, $type = 'file')
71         {
72                 if ($type == 'file') {
73                         $str = preg_quote('[' . str_replace('%', '%%', self::encode($s)) . ']');
74                 } else {
75                         $str = preg_quote('<' . str_replace('%', '%%', self::encode($s)) . '>');
76                 }
77
78                 return " AND " . (($table) ? DBA::escape($table) . '.' : '') . "file regexp '" . DBA::escape($str) . "' ";
79         }
80
81         /**
82          * Get file tags from array
83          *
84          * ex. given [music,video] return <music><video> or [music][video]
85          *
86          * @param array  $array A list of tags.
87          * @param string $type  Optional file type.
88          *
89          * @return string       A list of file tags.
90          */
91         public static function arrayToFile(array $array, string $type = 'file')
92         {
93                 $tag_list = '';
94                 if ($type == 'file') {
95                         $lbracket = '[';
96                         $rbracket = ']';
97                 } else {
98                         $lbracket = '<';
99                         $rbracket = '>';
100                 }
101
102                 foreach ($array as $item) {
103                         if (strlen($item)) {
104                                 $tag_list .= $lbracket . self::encode(trim($item)) . $rbracket;
105                         }
106                 }
107
108                 return $tag_list;
109         }
110
111         /**
112          * Get tag list from file tags
113          *
114          * ex. given <music><video>[friends], return [music,video] or [friends]
115          *
116          * @param string $file File tags
117          * @param string $type Optional file type.
118          *
119          * @return array        List of tag names.
120          */
121         public static function fileToArray(string $file, string $type = 'file')
122         {
123                 $matches = [];
124                 $return = [];
125
126                 if ($type == 'file') {
127                         $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
128                 } else {
129                         $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
130                 }
131
132                 if ($cnt) {
133                         foreach ($matches as $match) {
134                                 $return[] = self::decode($match[1]);
135                         }
136                 }
137
138                 return $return;
139         }
140
141         /**
142          * Get file tags from list
143          *
144          * ex. given music,video return <music><video> or [music][video]
145          * @param string $list A comma delimited list of tags.
146          * @param string $type Optional file type.
147          *
148          * @return string       A list of file tags.
149          * @deprecated since 2019.06 use arrayToFile() instead
150          */
151         public static function listToFile(string $list, string $type = 'file')
152         {
153                 $list_array = explode(',', $list);
154
155                 return self::arrayToFile($list_array, $type);
156         }
157
158         /**
159          * Get list from file tags
160          *
161          * ex. given <music><video>[friends], return music,video or friends
162          * @param string $file File tags
163          * @param string $type Optional file type.
164          *
165          * @return string       Comma delimited list of tag names.
166          * @deprecated since 2019.06 use fileToArray() instead
167          */
168         public static function fileToList(string $file, $type = 'file')
169         {
170                 return implode(',', self::fileToArray($file, $type));
171         }
172
173         /**
174          * Update file tags in PConfig
175          *
176          * @param int    $uid      Unique Identity.
177          * @param string $file_old Categories previously associated with an item
178          * @param string $file_new New list of categories for an item
179          * @param string $type     Optional file type.
180          *
181          * @return boolean          A value indicating success or failure.
182          * @throws \Exception
183          */
184         public static function updatePconfig(int $uid, string $file_old, string $file_new, string $type = 'file')
185         {
186                 if (!intval($uid)) {
187                         return false;
188                 } elseif ($file_old == $file_new) {
189                         return true;
190                 }
191
192                 $saved = DI::pConfig()->get($uid, 'system', 'filetags');
193
194                 if (strlen($saved)) {
195                         if ($type == 'file') {
196                                 $lbracket = '[';
197                                 $rbracket = ']';
198                                 $termtype = TERM_FILE;
199                         } else {
200                                 $lbracket = '<';
201                                 $rbracket = '>';
202                                 $termtype = TERM_CATEGORY;
203                         }
204
205                         $filetags_updated = $saved;
206
207                         // check for new tags to be added as filetags in pconfig
208                         $new_tags = [];
209                         foreach (self::fileToArray($file_new, $type) as $tag) {
210                                 if (!stristr($saved, $lbracket . self::encode($tag) . $rbracket)) {
211                                         $new_tags[] = $tag;
212                                 }
213                         }
214
215                         $filetags_updated .= self::arrayToFile($new_tags, $type);
216
217                         // check for deleted tags to be removed from filetags in pconfig
218                         $deleted_tags = [];
219                         foreach (self::fileToArray($file_old, $type) as $tag) {
220                                 if (!stristr($file_new, $lbracket . self::encode($tag) . $rbracket)) {
221                                         $deleted_tags[] = $tag;
222                                 }
223                         }
224
225                         foreach ($deleted_tags as $key => $tag) {
226                                 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
227                                         DBA::escape($tag),
228                                         intval(Term::OBJECT_TYPE_POST),
229                                         intval($termtype),
230                                         intval($uid));
231
232                                 if (DBA::isResult($r)) {
233                                         unset($deleted_tags[$key]);
234                                 } else {
235                                         $filetags_updated = str_replace($lbracket . self::encode($tag) . $rbracket, '', $filetags_updated);
236                                 }
237                         }
238
239                         if ($saved != $filetags_updated) {
240                                 DI::pConfig()->set($uid, 'system', 'filetags', $filetags_updated);
241                         }
242
243                         return true;
244                 } elseif (strlen($file_new)) {
245                         DI::pConfig()->set($uid, 'system', 'filetags', $file_new);
246                 }
247
248                 return true;
249         }
250
251         /**
252          * Add tag to file
253          *
254          * @param int    $uid     Unique identity.
255          * @param int    $item_id Item identity.
256          * @param string $file    File tag.
257          *
258          * @return boolean      A value indicating success or failure.
259          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260          */
261         public static function saveFile($uid, $item_id, $file)
262         {
263                 if (!intval($uid)) {
264                         return false;
265                 }
266
267                 $item = Item::selectFirst(['file'], ['id' => $item_id, 'uid' => $uid]);
268                 if (DBA::isResult($item)) {
269                         if (!stristr($item['file'], '[' . self::encode($file) . ']')) {
270                                 $fields = ['file' => $item['file'] . '[' . self::encode($file) . ']'];
271                                 Item::update($fields, ['id' => $item_id]);
272                         }
273
274                         $saved = DI::pConfig()->get($uid, 'system', 'filetags');
275
276                         if (!strlen($saved) || !stristr($saved, '[' . self::encode($file) . ']')) {
277                                 DI::pConfig()->set($uid, 'system', 'filetags', $saved . '[' . self::encode($file) . ']');
278                         }
279
280                         info(DI::l10n()->t('Item filed'));
281                 }
282
283                 return true;
284         }
285
286         /**
287          * Remove tag from file
288          *
289          * @param int     $uid     Unique identity.
290          * @param int     $item_id Item identity.
291          * @param string  $file    File tag.
292          * @param boolean $cat     Optional value indicating the term type (i.e. Category or File)
293          *
294          * @return boolean      A value indicating success or failure.
295          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
296          */
297         public static function unsaveFile($uid, $item_id, $file, $cat = false)
298         {
299                 if (!intval($uid)) {
300                         return false;
301                 }
302
303                 if ($cat == true) {
304                         $pattern = '<' . self::encode($file) . '>';
305                         $termtype = Term::CATEGORY;
306                 } else {
307                         $pattern = '[' . self::encode($file) . ']';
308                         $termtype = Term::FILE;
309                 }
310
311                 $item = Item::selectFirst(['file'], ['id' => $item_id, 'uid' => $uid]);
312
313                 if (!DBA::isResult($item)) {
314                         return false;
315                 }
316
317                 $fields = ['file' => str_replace($pattern, '', $item['file'])];
318
319                 Item::update($fields, ['id' => $item_id]);
320
321                 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
322                         DBA::escape($file),
323                         intval(Term::OBJECT_TYPE_POST),
324                         intval($termtype),
325                         intval($uid)
326                 );
327
328                 if (!DBA::isResult($r)) {
329                         $saved = DI::pConfig()->get($uid, 'system', 'filetags');
330                         DI::pConfig()->set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
331                 }
332
333                 return true;
334         }
335 }