]> git.mxchange.org Git - friendica.git/blob - src/Model/FileTag.php
Useless info messages removed
[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 use Friendica\Model\Post\Category;
27
28 /**
29  * This class handles FileTag related functions
30  *
31  * post categories and "save to file" use the same item.file table for storage.
32  * We will differentiate the different uses by wrapping categories in angle brackets
33  * and save to file categories in square brackets.
34  * To do this we need to escape these characters if they appear in our tag.
35  */
36 class FileTag
37 {
38         /**
39          * URL encode <, >, left and right brackets
40          *
41          * @param string $s String to be URL encoded.
42          *
43          * @return string   The URL encoded string.
44          */
45         public static function encode($s)
46         {
47                 return str_replace(['<', '>', '[', ']'], ['%3c', '%3e', '%5b', '%5d'], $s);
48         }
49
50         /**
51          * URL decode <, >, left and right brackets
52          *
53          * @param string $s The URL encoded string to be decoded
54          *
55          * @return string   The decoded string.
56          */
57         public static function decode($s)
58         {
59                 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
60         }
61
62         /**
63          * Query files for tag
64          *
65          * @param string $table The table to be queired.
66          * @param string $s     The search term
67          * @param string $type  Optional file type.
68          *
69          * @return string       Query string.
70          */
71         public static function fileQuery($table, $s, $type = 'file')
72         {
73                 if ($type == 'file') {
74                         $str = preg_quote('[' . str_replace('%', '%%', self::encode($s)) . ']');
75                 } else {
76                         $str = preg_quote('<' . str_replace('%', '%%', self::encode($s)) . '>');
77                 }
78
79                 return " AND " . (($table) ? DBA::escape($table) . '.' : '') . "file regexp '" . DBA::escape($str) . "' ";
80         }
81
82         /**
83          * Get file tags from array
84          *
85          * ex. given [music,video] return <music><video> or [music][video]
86          *
87          * @param array  $array A list of tags.
88          * @param string $type  Optional file type.
89          *
90          * @return string       A list of file tags.
91          */
92         public static function arrayToFile(array $array, string $type = 'file')
93         {
94                 $tag_list = '';
95                 if ($type == 'file') {
96                         $lbracket = '[';
97                         $rbracket = ']';
98                 } else {
99                         $lbracket = '<';
100                         $rbracket = '>';
101                 }
102
103                 foreach ($array as $item) {
104                         if (strlen($item)) {
105                                 $tag_list .= $lbracket . self::encode(trim($item)) . $rbracket;
106                         }
107                 }
108
109                 return $tag_list;
110         }
111
112         /**
113          * Get tag list from file tags
114          *
115          * ex. given <music><video>[friends], return [music,video] or [friends]
116          *
117          * @param string $file File tags
118          * @param string $type Optional file type.
119          *
120          * @return array        List of tag names.
121          */
122         public static function fileToArray(string $file, string $type = 'file')
123         {
124                 $matches = [];
125                 $return = [];
126
127                 if ($type == 'file') {
128                         $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
129                 } else {
130                         $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
131                 }
132
133                 if ($cnt) {
134                         foreach ($matches as $match) {
135                                 $return[] = self::decode($match[1]);
136                         }
137                 }
138
139                 return $return;
140         }
141
142         /**
143          * Get file tags from list
144          *
145          * ex. given music,video return <music><video> or [music][video]
146          * @param string $list A comma delimited list of tags.
147          * @param string $type Optional file type.
148          *
149          * @return string       A list of file tags.
150          * @deprecated since 2019.06 use arrayToFile() instead
151          */
152         public static function listToFile(string $list, string $type = 'file')
153         {
154                 $list_array = explode(',', $list);
155
156                 return self::arrayToFile($list_array, $type);
157         }
158
159         /**
160          * Get list from file tags
161          *
162          * ex. given <music><video>[friends], return music,video or friends
163          * @param string $file File tags
164          * @param string $type Optional file type.
165          *
166          * @return string       Comma delimited list of tag names.
167          * @deprecated since 2019.06 use fileToArray() instead
168          */
169         public static function fileToList(string $file, $type = 'file')
170         {
171                 return implode(',', self::fileToArray($file, $type));
172         }
173
174         /**
175          * Update file tags in PConfig
176          *
177          * @param int    $uid      Unique Identity.
178          * @param string $file_old Categories previously associated with an item
179          * @param string $file_new New list of categories for an item
180          * @param string $type     Optional file type.
181          *
182          * @return boolean          A value indicating success or failure.
183          * @throws \Exception
184          */
185         public static function updatePconfig(int $uid, string $file_old, string $file_new, string $type = 'file')
186         {
187                 if (!intval($uid)) {
188                         return false;
189                 } elseif ($file_old == $file_new) {
190                         return true;
191                 }
192
193                 $saved = DI::pConfig()->get($uid, 'system', 'filetags');
194
195                 if (strlen($saved)) {
196                         if ($type == 'file') {
197                                 $lbracket = '[';
198                                 $rbracket = ']';
199                                 $termtype = Category::FILE;
200                         } else {
201                                 $lbracket = '<';
202                                 $rbracket = '>';
203                                 $termtype = Category::CATEGORY;
204                         }
205
206                         $filetags_updated = $saved;
207
208                         // check for new tags to be added as filetags in pconfig
209                         $new_tags = [];
210                         foreach (self::fileToArray($file_new, $type) as $tag) {
211                                 if (!stristr($saved, $lbracket . self::encode($tag) . $rbracket)) {
212                                         $new_tags[] = $tag;
213                                 }
214                         }
215
216                         $filetags_updated .= self::arrayToFile($new_tags, $type);
217
218                         // check for deleted tags to be removed from filetags in pconfig
219                         $deleted_tags = [];
220                         foreach (self::fileToArray($file_old, $type) as $tag) {
221                                 if (!stristr($file_new, $lbracket . self::encode($tag) . $rbracket)) {
222                                         $deleted_tags[] = $tag;
223                                 }
224                         }
225
226                         foreach ($deleted_tags as $key => $tag) {
227                                 if (DBA::exists('category-view', ['name' => $tag, 'type' => $termtype, 'uid' => $uid])) {
228                                         unset($deleted_tags[$key]);
229                                 } else {
230                                         $filetags_updated = str_replace($lbracket . self::encode($tag) . $rbracket, '', $filetags_updated);
231                                 }
232                         }
233
234                         if ($saved != $filetags_updated) {
235                                 DI::pConfig()->set($uid, 'system', 'filetags', $filetags_updated);
236                         }
237
238                         return true;
239                 } elseif (strlen($file_new)) {
240                         DI::pConfig()->set($uid, 'system', 'filetags', $file_new);
241                 }
242
243                 return true;
244         }
245
246         /**
247          * Add tag to file
248          *
249          * @param int    $uid     Unique identity.
250          * @param int    $item_id Item identity.
251          * @param string $file    File tag.
252          *
253          * @return boolean      A value indicating success or failure.
254          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255          */
256         public static function saveFile($uid, $item_id, $file)
257         {
258                 if (!intval($uid)) {
259                         return false;
260                 }
261
262                 $item = Item::selectFirst(['file'], ['id' => $item_id, 'uid' => $uid]);
263                 if (DBA::isResult($item)) {
264                         if (!stristr($item['file'], '[' . self::encode($file) . ']')) {
265                                 $fields = ['file' => $item['file'] . '[' . self::encode($file) . ']'];
266                                 Item::update($fields, ['id' => $item_id]);
267                         }
268
269                         $saved = DI::pConfig()->get($uid, 'system', 'filetags');
270
271                         if (!strlen($saved) || !stristr($saved, '[' . self::encode($file) . ']')) {
272                                 DI::pConfig()->set($uid, 'system', 'filetags', $saved . '[' . self::encode($file) . ']');
273                         }
274                 }
275
276                 return true;
277         }
278
279         /**
280          * Remove tag from file
281          *
282          * @param int     $uid     Unique identity.
283          * @param int     $item_id Item identity.
284          * @param string  $file    File tag.
285          * @param boolean $cat     Optional value indicating the term type (i.e. Category or File)
286          *
287          * @return boolean      A value indicating success or failure.
288          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289          */
290         public static function unsaveFile($uid, $item_id, $file, $cat = false)
291         {
292                 if (!intval($uid)) {
293                         return false;
294                 }
295
296                 if ($cat == true) {
297                         $pattern = '<' . self::encode($file) . '>';
298                         $termtype = Category::CATEGORY;
299                 } else {
300                         $pattern = '[' . self::encode($file) . ']';
301                         $termtype = Category::FILE;
302                 }
303
304                 $item = Item::selectFirst(['file'], ['id' => $item_id, 'uid' => $uid]);
305
306                 if (!DBA::isResult($item)) {
307                         return false;
308                 }
309
310                 $fields = ['file' => str_replace($pattern, '', $item['file'])];
311
312                 Item::update($fields, ['id' => $item_id]);
313
314                 if (!DBA::exists('category-view', ['name' => $file, 'type' => $termtype, 'uid' => $uid])) {
315                         $saved = DI::pConfig()->get($uid, 'system', 'filetags');
316                         DI::pConfig()->set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
317                 }
318
319                 return true;
320         }
321 }