PluginProbe
User Access Manager / 2.0.8
User Access Manager v2.0.8
2.3.20 2.3.19 2.3.18 2.3.17 2.3.16 2.3.15 2.3.14 2.3.13 trunk 0.6 0.6.1 0.6.2 0.7 0.7 Beta 0.7.0.1 0.8 0.8.0.1 0.8.0.2 0.9 0.9.1 0.9.1.1 0.9.1.2 0.9.1.3 0.9.1.4 1.0 All 136 releases
user-access-manager / src / UserAccessManager / Controller / FrontendController.php

FrontendController.php in User Access Manager 2.0.8, at src/UserAccessManager/Controller/FrontendController.php

1,083 lines 31.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * FrontendController.php
4 *
5 * The FrontendController class file.
6 *
7 * PHP versions 5
8 *
9 * @author Alexander Schneider <alexanderschneider85@gmail.com>
10 * @copyright 2008-2017 Alexander Schneider
11 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
12 * @version SVN: $id$
13 * @link http://wordpress.org/extend/plugins/user-access-manager/
14 */
15 namespace UserAccessManager\Controller;
16
17 use UserAccessManager\AccessHandler\AccessHandler;
18 use UserAccessManager\Cache\Cache;
19 use UserAccessManager\Config\Config;
20 use UserAccessManager\Database\Database;
21 use UserAccessManager\FileHandler\FileHandler;
22 use UserAccessManager\FileHandler\FileObject;
23 use UserAccessManager\FileHandler\FileObjectFactory;
24 use UserAccessManager\ObjectHandler\ObjectHandler;
25 use UserAccessManager\UserAccessManager;
26 use UserAccessManager\UserGroup\UserGroup;
27 use UserAccessManager\Util\Util;
28 use UserAccessManager\Wrapper\Php;
29 use UserAccessManager\Wrapper\Wordpress;
30
31 /**
32 * Class FrontendController
33 *
34 * @package UserAccessManager\Controller
35 */
36 class FrontendController extends Controller
37 {
38 const HANDLE_STYLE_LOGIN_FORM = 'UserAccessManagerLoginForm';
39 const POST_URL_CACHE_KEY = 'PostUrls';
40 const POST_COUNTS_CACHE_KEY = 'WpPostCounts';
41
42 /**
43 * @var Database
44 */
45 private $database;
46
47 /**
48 * @var Cache
49 */
50 private $cache;
51
52 /**
53 * @var Util
54 */
55 private $util;
56
57 /**
58 * @var ObjectHandler
59 */
60 private $objectHandler;
61
62 /**
63 * @var AccessHandler
64 */
65 private $accessHandler;
66
67 /**
68 * @var FileHandler
69 */
70 private $fileHandler;
71
72 /**
73 * @var FileObjectFactory
74 */
75 private $fileObjectFactory;
76
77 /**
78 * FrontendController constructor.
79 *
80 * @param Php $php
81 * @param Wordpress $wordpress
82 * @param Config $config
83 * @param Database $database
84 * @param Util $util
85 * @param Cache $cache
86 * @param ObjectHandler $objectHandler
87 * @param AccessHandler $accessHandler
88 * @param FileHandler $fileHandler
89 * @param FileObjectFactory $fileObjectFactory
90 */
91 public function __construct(
92 Php $php,
93 Wordpress $wordpress,
94 Config $config,
95 Database $database,
96 Util $util,
97 Cache $cache,
98 ObjectHandler $objectHandler,
99 AccessHandler $accessHandler,
100 FileHandler $fileHandler,
101 FileObjectFactory $fileObjectFactory
102 ) {
103 parent::__construct($php, $wordpress, $config);
104 $this->database = $database;
105 $this->util = $util;
106 $this->cache = $cache;
107 $this->objectHandler = $objectHandler;
108 $this->accessHandler = $accessHandler;
109 $this->fileHandler = $fileHandler;
110 $this->fileObjectFactory = $fileObjectFactory;
111 }
112
113 /**
114 * Functions for other content.
115 */
116
117 /**
118 * Register all other styles.
119 */
120 private function registerStylesAndScripts()
121 {
122 $urlPath = $this->config->getUrlPath();
123
124 $this->wordpress->registerStyle(
125 self::HANDLE_STYLE_LOGIN_FORM,
126 $urlPath.'assets/css/uamLoginForm.css',
127 [],
128 UserAccessManager::VERSION,
129 'screen'
130 );
131 }
132
133 /**
134 * The function for the wp_enqueue_scripts action.
135 */
136 public function enqueueStylesAndScripts()
137 {
138 $this->registerStylesAndScripts();
139 $this->wordpress->enqueueStyle(self::HANDLE_STYLE_LOGIN_FORM);
140 }
141
142 /*
143 * Functions for the blog content.
144 */
145
146 /**
147 * Manipulates the wordpress query object to filter content.
148 *
149 * @param \WP_Query $wpQuery The wordpress query object.
150 */
151 public function parseQuery($wpQuery)
152 {
153 if (isset($wpQuery->query_vars['suppress_filters']) === true
154 && $wpQuery->query_vars['suppress_filters'] === true
155 ) {
156 $excludedPosts = $this->accessHandler->getExcludedPosts();
157
158 if (count($excludedPosts) > 0) {
159 $postsNotIn = (isset($wpQuery->query_vars['post__not_in']) === true) ?
160 $wpQuery->query_vars['post__not_in'] : [];
161
162 $wpQuery->query_vars['post__not_in'] = array_unique(
163 array_merge($postsNotIn, $excludedPosts)
164 );
165 }
166 }
167 }
168
169 /**
170 * Returns the admin hint.
171 *
172 * @param string $objectType The object type.
173 * @param integer $objectId The object id we want to check.
174 * @param string $text The text on which we want to append the hint.
175 *
176 * @return string
177 */
178 public function adminOutput($objectType, $objectId, $text = null)
179 {
180 $output = '';
181
182 if ($this->config->atAdminPanel() === false
183 && $this->config->blogAdminHint() === true
184 ) {
185 $hintText = $this->config->getBlogAdminHintText();
186
187 if ($text !== null && $this->util->endsWith($text, $hintText) === true) {
188 return $output;
189 }
190
191 if ($this->accessHandler->userIsAdmin($this->wordpress->getCurrentUser()->ID) === true
192 && count($this->accessHandler->getUserGroupsForObject($objectType, $objectId)) > 0
193 ) {
194 $output .= $hintText;
195 }
196 }
197
198 return $output;
199 }
200
201 /**
202 * Returns the login bar.
203 *
204 * @return string
205 */
206 public function getLoginFormHtml()
207 {
208 $loginForm = '';
209
210 if ($this->wordpress->isUserLoggedIn() === false) {
211 $loginForm = $this->getIncludeContents('LoginForm.php');
212 }
213
214 return $this->wordpress->applyFilters('uam_login_form', $loginForm);
215 }
216
217 /**
218 * Tries to get the post from the given mixed data.
219 *
220 * @param mixed $post
221 *
222 * @return false|\WP_Post
223 */
224 private function getPost($post)
225 {
226 if ($post instanceof \WP_post) {
227 return $post;
228 } elseif (is_int($post) === true) {
229 return $this->objectHandler->getPost($post);
230 } elseif ($post instanceof \stdClass && isset($post->ID)) {
231 return $this->objectHandler->getPost($post->ID);
232 }
233
234 return false;
235 }
236
237 /**
238 * Modifies the content of the post by the given settings.
239 *
240 * @param \WP_Post $post The current post.
241 * @param bool $locked
242 *
243 * @return null|\WP_Post
244 */
245 private function processPost(\WP_Post $post, &$locked = null)
246 {
247 $post->post_title .= $this->adminOutput($post->post_type, $post->ID);
248 $locked = ($this->accessHandler->checkObjectAccess($post->post_type, $post->ID) === false);
249
250 if ($locked === true) {
251 if ($this->config->hidePostType($post->post_type) === true
252 || $this->config->atAdminPanel() === true
253 ) {
254 return null;
255 }
256
257 $uamPostContent = $this->config->getPostTypeContent($post->post_type);
258
259 if ($post->post_type === 'post'
260 && $this->config->showPostContentBeforeMore() === true
261 && preg_match('/<!--more(.*?)?-->/', $post->post_content, $matches)
262 ) {
263 $uamPostContent = explode($matches[0], $post->post_content)[0]." ".$uamPostContent;
264 }
265
266 $post->post_content = stripslashes($uamPostContent);
267
268 if ($this->config->hidePostTypeTitle($post->post_type) === true) {
269 $post->post_title = $this->config->getPostTypeTitle($post->post_type);
270 }
271
272 if ($this->config->hidePostTypeComments($post->post_type) === true) {
273 $post->comment_status = 'close';
274 }
275 }
276
277 return $post;
278 }
279
280 /**
281 * The function for the the_posts filter.
282 *
283 * @param array $rawPosts The posts.
284 *
285 * @return array
286 */
287 public function showPosts($rawPosts = [])
288 {
289 $showPosts = [];
290
291 if ($this->wordpress->isFeed() === false || $this->config->protectFeed() === true) {
292 foreach ($rawPosts as $rawPost) {
293 $post = $this->getPost($rawPost);
294
295 if ($post !== false) {
296 $post = $this->processPost($post);
297
298 if ($post !== null) {
299 $showPosts[] = $post;
300 }
301 } else {
302 $showPosts[] = $rawPost;
303 }
304 }
305 } else {
306 $showPosts = $rawPosts;
307 }
308
309 return $showPosts;
310 }
311
312 /**
313 * The function for the get_pages filter.
314 *
315 * @param \WP_Post[] $rawPages The pages.
316 *
317 * @return array
318 */
319 public function showPages($rawPages = [])
320 {
321 $showPages = [];
322
323 foreach ($rawPages as $rawPage) {
324 $page = $this->getPost($rawPage);
325
326 if ($page !== false) {
327 $page = $this->processPost($page);
328
329 if ($page !== null) {
330 $showPages[] = $page;
331 }
332 } else {
333 $showPages[] = $rawPage;
334 }
335 }
336
337 $rawPages = $showPages;
338
339 return $rawPages;
340 }
341
342 /**
343 * Needed to prevent the form against the auto <br>s of wordpress
344 *
345 * @param string $content
346 *
347 * @return string
348 */
349 public function showContent($content)
350 {
351 return (string)str_replace('[LOGIN_FORM]', $this->getLoginFormHtml(), $content);
352 }
353
354 /**
355 * The function for the posts_where_paged filter.
356 *
357 * @param string $query The where sql statement.
358 *
359 * @return string
360 */
361 public function showPostSql($query)
362 {
363 $excludedPosts = $this->accessHandler->getExcludedPosts();
364
365 if (count($excludedPosts) > 0) {
366 $excludedPostsStr = implode(', ', $excludedPosts);
367 $query .= " AND {$this->database->getPostsTable()}.ID NOT IN ($excludedPostsStr) ";
368 }
369
370 return $query;
371 }
372
373 /**
374 * Function for the wp_count_posts filter.
375 *
376 * @param \stdClass $counts
377 * @param string $type
378 * @param string $perm
379 *
380 * @return \stdClass
381 */
382 public function showPostCount($counts, $type, $perm)
383 {
384 $cachedCounts = $this->cache->getFromCache(self::POST_COUNTS_CACHE_KEY);
385
386 if ($cachedCounts === null) {
387 $excludedPosts = $this->accessHandler->getExcludedPosts();
388
389 if (count($excludedPosts) > 0) {
390 $excludedPosts = implode('\', \'', $excludedPosts);
391
392 $query = "SELECT post_status, COUNT(*) AS num_posts
393 FROM {$this->database->getPostsTable()}
394 WHERE post_type = %s
395 AND ID NOT IN ('{$excludedPosts}')";
396
397 if ('readable' === $perm && $this->wordpress->isUserLoggedIn() === true) {
398 $postTypeObject = $this->wordpress->getPostTypeObject($type);
399
400 if ($this->wordpress->currentUserCan($postTypeObject->cap->read_private_posts) === false) {
401 $query .= $this->database->prepare(
402 ' AND (post_status != \'private\' OR (post_author = %d AND post_status = \'private\'))',
403 $this->wordpress->getCurrentUser()->ID
404 );
405 }
406 }
407
408 $query .= ' GROUP BY post_status';
409
410 $results = (array)$this->database->getResults(
411 $this->database->prepare($query, $type),
412 ARRAY_A
413 );
414
415 foreach ($results as $result) {
416 if (isset($counts->{$result['post_status']})) {
417 $counts->{$result['post_status']} = $result['num_posts'];
418 }
419 }
420 }
421
422 $cachedCounts = $counts;
423 $this->cache->addToCache(self::POST_COUNTS_CACHE_KEY, $cachedCounts);
424 }
425
426 return $cachedCounts;
427 }
428
429 /**
430 * Sets the excluded terms as argument.
431 *
432 * @param array $arguments
433 *
434 * @return array
435 */
436 public function getTermArguments(array $arguments)
437 {
438 $exclude = (isset($arguments['exclude']) === true) ?
439 $this->wordpress->parseIdList($arguments['exclude']) : [];
440 $arguments['exclude'] = array_merge($exclude, $this->accessHandler->getExcludedTerms());
441 $arguments['exclude'] = array_unique($arguments['exclude']);
442
443 return $arguments;
444 }
445
446 /**
447 * The function for the comments_array filter.
448 *
449 * @param \WP_Comment[] $comments The comments.
450 *
451 * @return array
452 */
453 public function showComment($comments = [])
454 {
455 $showComments = [];
456
457 foreach ($comments as $comment) {
458 $post = $this->objectHandler->getPost($comment->comment_post_ID);
459
460 if ($post !== false
461 && $this->accessHandler->checkObjectAccess($post->post_type, $post->ID) === false
462 ) {
463 if ($this->config->hidePostTypeComments($post->post_type) === true
464 || $this->config->hidePostType($post->post_type) === true
465 || $this->config->atAdminPanel() === true
466 ) {
467 continue;
468 }
469
470 $comment->comment_content = $this->config->getPostTypeCommentContent($post->post_type);
471 }
472
473 $showComments[] = $comment;
474 }
475
476 return $showComments;
477 }
478
479 /**
480 * The function for the get_ancestors filter.
481 *
482 * @param array $ancestors
483 * @param int $objectId
484 * @param string $objectType
485 *
486 * @return array
487 */
488 public function showAncestors($ancestors, $objectId, $objectType)
489 {
490 if ($this->config->lockRecursive() === true
491 && $this->accessHandler->checkObjectAccess($objectType, $objectId) === false
492 ) {
493 return [];
494 }
495
496 foreach ($ancestors as $key => $ancestorId) {
497 if ($this->accessHandler->checkObjectAccess($objectType, $ancestorId) === false) {
498 unset($ancestors[$key]);
499 }
500 }
501
502 return $ancestors;
503 }
504
505 /**
506 * The function for the get_previous_post_where and
507 * the get_next_post_where filter.
508 *
509 * @param string $query The current sql string.
510 *
511 * @return string
512 */
513 public function showNextPreviousPost($query)
514 {
515 $excludedPosts = $this->accessHandler->getExcludedPosts();
516
517 if (count($excludedPosts) > 0) {
518 $excludedPosts = implode(', ', $excludedPosts);
519 $query .= " AND p.ID NOT IN ({$excludedPosts}) ";
520 }
521
522 return $query;
523 }
524
525 /**
526 * Returns the post count for the term.
527 *
528 * @param string $termType
529 * @param int $termId
530 *
531 * @return int
532 */
533 private function getVisibleElementsCount($termType, $termId)
534 {
535 $count = 0;
536
537 $fullTerms = [$termId => $termType];
538 $termTreeMap = $this->objectHandler->getTermTreeMap();
539
540 if (isset($termTreeMap[ObjectHandler::TREE_MAP_CHILDREN][$termType]) === true
541 && isset($termTreeMap[ObjectHandler::TREE_MAP_CHILDREN][$termType][$termId]) === true
542 ) {
543 $fullTerms += $termTreeMap[ObjectHandler::TREE_MAP_CHILDREN][$termType][$termId];
544 }
545
546 $posts = [];
547 $termPostMap = $this->objectHandler->getTermPostMap();
548
549 foreach ($fullTerms as $fullTermId => $fullTermType) {
550 if (isset($termPostMap[$fullTermId]) === true) {
551 $posts += $termPostMap[$fullTermId];
552 }
553 }
554
555 foreach ($posts as $postId => $postType) {
556 if ($this->config->hidePostType($postType) === false
557 || $this->accessHandler->checkObjectAccess(ObjectHandler::GENERAL_POST_OBJECT_TYPE, $postId) === true
558 ) {
559 $count++;
560 }
561 }
562
563 return $count;
564 }
565
566 /**
567 * Modifies the content of the term by the given settings.
568 *
569 * @param \WP_Term $term The current term.
570 * @param bool $isEmpty
571 *
572 * @return mixed
573 */
574 private function processTerm($term, &$isEmpty = null)
575 {
576 $isEmpty = false;
577
578 if (($term instanceof \WP_Term) === false) {
579 return $term;
580 }
581
582 if ($this->accessHandler->checkObjectAccess($term->taxonomy, $term->term_id) === false) {
583 return null;
584 }
585
586 $term->name .= $this->adminOutput($term->taxonomy, $term->term_id, $term->name);
587 $term->count = $this->getVisibleElementsCount($term->taxonomy, $term->term_id);
588
589 //For categories
590 if ($term->count <= 0
591 && $this->config->atAdminPanel() === false
592 && $this->config->hideEmptyTaxonomy($term->taxonomy) === true
593 ) {
594 $isEmpty = true;
595 }
596
597 if ($this->config->lockRecursive() === false) {
598 $currentTerm = $term;
599
600 while ($currentTerm->parent != 0) {
601 $currentTerm = $this->objectHandler->getTerm($currentTerm->parent);
602
603 if ($currentTerm === false) {
604 break;
605 }
606
607 $access = $this->accessHandler->checkObjectAccess(
608 $currentTerm->taxonomy,
609 $currentTerm->term_id
610 );
611
612 if ($access === true) {
613 $term->parent = $currentTerm->term_id;
614 break;
615 }
616 }
617 }
618
619 return $term;
620 }
621
622 /**
623 * The function for the get_term filter.
624 *
625 * @param \WP_Term $term
626 *
627 * @return null|object
628 */
629 public function showTerm($term)
630 {
631 return $this->processTerm($term);
632 }
633
634 /**
635 * The function for the get_terms filter.
636 *
637 * @param array $terms The terms.
638 *
639 * @return array
640 */
641 public function showTerms($terms = [])
642 {
643 foreach ($terms as $key => $term) {
644 $isNumeric = (is_numeric($term) === true);
645
646 if ($isNumeric === true) {
647 if ((int)$term === 0) {
648 unset($terms[$key]);
649 continue;
650 }
651
652 $term = $this->objectHandler->getTerm($term);
653 }
654
655 if (($term instanceof \WP_Term) === false) {
656 continue;
657 }
658
659 $term = $this->processTerm($term, $isEmpty);
660
661 if ($term !== null && $isEmpty === false) {
662 $terms[$key] = ($isNumeric === true) ? $term->term_id : $term;
663 } else {
664 unset($terms[$key]);
665 }
666 }
667
668 return $terms;
669 }
670
671 /**
672 * The function for the wp_get_nav_menu_items filter.
673 *
674 * @param array $items The menu item.
675 *
676 * @return array
677 */
678 public function showCustomMenu($items)
679 {
680 $showItems = [];
681
682 foreach ($items as $key => $item) {
683 $item->title .= $this->adminOutput($item->object, $item->object_id, $item->title);
684
685 if ($this->objectHandler->isPostType($item->object) === true) {
686 if ($this->accessHandler->checkObjectAccess($item->object, $item->object_id) === false) {
687 if ($this->config->hidePostType($item->object) === true
688 || $this->config->atAdminPanel() === true
689 ) {
690 continue;
691 }
692
693 if ($this->config->hidePostTypeTitle($item->object) === true) {
694 $item->title = $this->config->getPostTypeTitle($item->object);
695 }
696 }
697
698 $showItems[$key] = $item;
699 } elseif ($this->objectHandler->isTaxonomy($item->object) === true) {
700 $term = $this->objectHandler->getTerm($item->object_id);
701
702 if ($term !== false) {
703 $term = $this->processTerm($term, $isEmpty);
704
705 if ($term !== null && $isEmpty === false) {
706 $showItems[$key] = $item;
707 }
708 }
709 } else {
710 $showItems[$key] = $item;
711 }
712 }
713
714 return $showItems;
715 }
716
717 /**
718 * The function for the edit_post_link filter.
719 *
720 * @param string $link The edit link.
721 * @param integer $postId The _iId of the post.
722 *
723 * @return string
724 */
725 public function showGroupMembership($link, $postId)
726 {
727 $userGroups = $this->accessHandler->getFilteredUserGroupsForObject(
728 ObjectHandler::GENERAL_POST_OBJECT_TYPE,
729 $postId
730 );
731
732 if (count($userGroups) > 0) {
733 $escapedGroups = array_map(
734 function (UserGroup $group) {
735 return htmlentities($group->getName());
736 },
737 $userGroups
738 );
739
740 $link .= ' | '.TXT_UAM_ASSIGNED_GROUPS.': ';
741 $link .= implode(', ', $escapedGroups);
742 }
743
744 return $link;
745 }
746
747 /**
748 * Checks if we allowed show the login form.
749 *
750 * @return bool
751 */
752 public function showLoginForm()
753 {
754 return $this->wordpress->isSingle() === true || $this->wordpress->isPage() === true;
755 }
756
757 /**
758 * Returns the login url.
759 *
760 * @var array $parameters
761 *
762 * @return mixed
763 */
764 public function getLoginUrl(array $parameters = [])
765 {
766 $loginUrl = $this->wordpress->getBlogInfo('wpurl').'/wp-login.php';
767 $loginUrl .= (count($parameters) > 0) ? '?'.http_build_query($parameters) : '';
768 return $this->wordpress->applyFilters('uam_login_form_url', $loginUrl, $parameters);
769 }
770
771 /**
772 * Returns the login redirect url.
773 *
774 * @return mixed
775 */
776 public function getRedirectLoginUrl()
777 {
778 $loginUrl = $this->wordpress->getBlogInfo('wpurl')
779 .'/wp-login.php?redirect_to='.urlencode($_SERVER['REQUEST_URI']);
780 return $this->wordpress->applyFilters('uam_login_url', $loginUrl);
781 }
782
783 /**
784 * Returns the user login name.
785 *
786 * @return string
787 */
788 public function getUserLogin()
789 {
790 $userLogin = $this->getRequestParameter('log');
791 return $this->wordpress->escHtml(stripslashes($userLogin));
792 }
793
794
795 /*
796 * Functions for the redirection and files.
797 */
798
799 /**
800 * Returns the post by the given url.
801 *
802 * @param string $url The url of the post(attachment).
803 *
804 * @return int
805 */
806 public function getPostIdByUrl($url)
807 {
808 $postUrls = (array)$this->cache->getFromCache(self::POST_URL_CACHE_KEY);
809
810 if (isset($postUrls[$url]) === true) {
811 return $postUrls[$url];
812 }
813
814 $postUrls[$url] = null;
815
816 //Filter edit string
817 $newUrlPieces = preg_split('/-e[0-9]{1,}/', $url);
818 $newUrl = (count($newUrlPieces) === 2) ? $newUrlPieces[0].$newUrlPieces[1] : $newUrlPieces[0];
819
820 //Filter size
821 $newUrlPieces = preg_split('/-[0-9]{1,}x[0-9]{1,}(_[a-z])?/', $newUrl);
822 $newUrl = (count($newUrlPieces) === 2) ? $newUrlPieces[0].$newUrlPieces[1] : $newUrlPieces[0];
823 $newUrl = preg_replace('/\-pdf\.jpg$/', '.pdf', $newUrl);
824
825 $query = $this->database->prepare(
826 "SELECT ID
827 FROM {$this->database->getPostsTable()}
828 WHERE guid = '%s'
829 LIMIT 1",
830 $newUrl
831 );
832
833 $dbPost = $this->database->getRow($query);
834
835 if ($dbPost !== null) {
836 $postUrls[$url] = $dbPost->ID;
837 $this->cache->addToCache(self::POST_URL_CACHE_KEY, $postUrls);
838 }
839
840 return $postUrls[$url];
841 }
842
843 /**
844 * Returns the file object by the given type and url.
845 *
846 * @param string $objectType The type of the requested file.
847 * @param string $objectUrl The file url.
848 *
849 * @return null|FileObject
850 */
851 private function getFileSettingsByType($objectType, $objectUrl)
852 {
853 $fileObject = null;
854
855 if ($objectType === ObjectHandler::ATTACHMENT_OBJECT_TYPE) {
856 $uploadDirs = $this->wordpress->getUploadDir();
857 $uploadDir = str_replace(ABSPATH, '/', $uploadDirs['basedir']);
858 $regex = '/.*'.str_replace('/', '\/', $uploadDir).'\//i';
859 $cleanObjectUrl = preg_replace($regex, '', $objectUrl);
860 $uploadUrl = str_replace('/files', $uploadDir, $uploadDirs['baseurl']);
861 $objectUrl = rtrim($uploadUrl, '/').'/'.ltrim($cleanObjectUrl, '/');
862
863 $post = $this->objectHandler->getPost($this->getPostIdByUrl($objectUrl));
864
865 if ($post !== false
866 && $post->post_type === ObjectHandler::ATTACHMENT_OBJECT_TYPE
867 ) {
868 $multiPath = str_replace('/files', $uploadDir, $uploadDirs['baseurl']);
869
870 $fileObject = $this->fileObjectFactory->createFileObject(
871 $post->ID,
872 $objectType,
873 $uploadDirs['basedir'].str_replace($multiPath, '', $objectUrl),
874 $this->wordpress->attachmentIsImage($post->ID)
875 );
876 }
877 } else {
878 $extraParameter = $this->getRequestParameter('uamextra');
879
880 $fileObject = $this->wordpress->applyFilters(
881 'uam_get_file_settings_by_type',
882 $fileObject,
883 $objectType,
884 $objectUrl,
885 $extraParameter
886 );
887 }
888
889 return $fileObject;
890 }
891
892 /**
893 * Delivers the content of the requested file.
894 *
895 * @param string $objectType The type of the requested file.
896 * @param string $objectUrl The file url.
897 */
898 public function getFile($objectType, $objectUrl)
899 {
900 $fileObject = $this->getFileSettingsByType($objectType, $objectUrl);
901
902 if ($fileObject === null) {
903 return;
904 }
905
906 if ($this->accessHandler->checkObjectAccess($fileObject->getType(), $fileObject->getId()) === true) {
907 $file = $fileObject->getFile();
908 } elseif ($fileObject->isImage() === true) {
909 $realPath = $this->config->getRealPath();
910 $file = $realPath.'assets/gfx/noAccessPic.png';
911 } else {
912 $this->wordpress->wpDie(TXT_UAM_NO_RIGHTS_MESSAGE, TXT_UAM_NO_RIGHTS_TITLE, ['response' => 403]);
913 return;
914 }
915
916 $this->fileHandler->getFile($file, $fileObject->isImage());
917 }
918
919 /**
920 * Redirects the user to his destination.
921 *
922 * @param bool $checkPosts
923 */
924 public function redirectUser($checkPosts = true)
925 {
926 if ($checkPosts === true) {
927 $posts = (array)$this->wordpress->getWpQuery()->get_posts();
928
929 foreach ($posts as $post) {
930 if ($this->accessHandler->checkObjectAccess($post->post_type, $post->ID)) {
931 return;
932 }
933 }
934 }
935
936 $permalink = null;
937 $redirect = $this->config->getRedirect();
938
939 if ($redirect === 'custom_page') {
940 $redirectCustomPage = $this->config->getRedirectCustomPage();
941 $post = $this->objectHandler->getPost($redirectCustomPage);
942 $url = null;
943
944 if ($post !== false) {
945 $url = $post->guid;
946 $permalink = $this->wordpress->getPageLink($post);
947 }
948 } elseif ($redirect === 'custom_url') {
949 $url = $this->config->getRedirectCustomUrl();
950 } else {
951 $url = $this->wordpress->getHomeUrl('/');
952 }
953
954 $currentUrl = $this->util->getCurrentUrl();
955
956 if ($url !== null && $url !== $currentUrl && $permalink !== $currentUrl) {
957 $this->wordpress->wpRedirect($url);
958 return;
959 }
960 }
961
962 /**
963 * Redirects to a page or to content.
964 *
965 * @param string $headers The headers which are given from wordpress.
966 * @param object $pageParams The params of the current page.
967 *
968 * @return string
969 */
970 public function redirect($headers, $pageParams)
971 {
972 $fileUrl = $this->getRequestParameter('uamgetfile');
973 $fileType = $this->getRequestParameter('uamfiletype');
974
975 if ($fileUrl !== null && $fileType !== null) {
976 $this->getFile($fileType, $fileUrl);
977 } elseif ($this->config->atAdminPanel() === false
978 && $this->config->getRedirect() !== 'false'
979 ) {
980 $objectType = null;
981 $objectId = null;
982
983 if (isset($pageParams->query_vars['p']) === true) {
984 $objectType = ObjectHandler::GENERAL_POST_OBJECT_TYPE;
985 $objectId = $pageParams->query_vars['p'];
986 } elseif (isset($pageParams->query_vars['page_id']) === true) {
987 $objectType = ObjectHandler::GENERAL_POST_OBJECT_TYPE;
988 $objectId = $pageParams->query_vars['page_id'];
989 } elseif (isset($pageParams->query_vars['cat_id']) === true) {
990 $objectType = ObjectHandler::GENERAL_TERM_OBJECT_TYPE;
991 $objectId = $pageParams->query_vars['cat_id'];
992 } elseif (isset($pageParams->query_vars['name']) === true) {
993 $postableTypes = implode('\',\'', $this->objectHandler->getPostTypes());
994
995 $query = $this->database->prepare(
996 "SELECT ID
997 FROM {$this->database->getPostsTable()}
998 WHERE post_name = %s
999 AND post_type IN ('{$postableTypes}')",
1000 $pageParams->query_vars['name']
1001 );
1002
1003 $objectType = ObjectHandler::GENERAL_POST_OBJECT_TYPE;
1004 $objectId = (int)$this->database->getVariable($query);
1005 } elseif (isset($pageParams->query_vars['pagename']) === true) {
1006 $object = $this->wordpress->getPageByPath($pageParams->query_vars['pagename']);
1007
1008 if ($object !== null) {
1009 $objectType = $object->post_type;
1010 $objectId = $object->ID;
1011 }
1012 }
1013
1014 if ($this->accessHandler->checkObjectAccess($objectType, $objectId) === false) {
1015 $this->redirectUser(false);
1016 }
1017 }
1018
1019 return $headers;
1020 }
1021
1022 /**
1023 * Returns the url for a locked file.
1024 *
1025 * @param string $url The base url.
1026 * @param integer $id The _iId of the file.
1027 *
1028 * @return string
1029 */
1030 public function getFileUrl($url, $id)
1031 {
1032 if ($this->config->isPermalinksActive() === false && $this->config->lockFile() === true) {
1033 $post = $this->objectHandler->getPost($id);
1034
1035 if ($post !== null) {
1036 $type = explode('/', $post->post_mime_type);
1037 $type = (isset($type[1]) === true) ? $type[1] : $type[0];
1038
1039 $lockedFileTypes = $this->config->getLockedFileTypes();
1040 $fileTypes = explode(',', $lockedFileTypes);
1041
1042 if ($lockedFileTypes === 'all' || in_array($type, $fileTypes) === true) {
1043 $url = $this->wordpress->getHomeUrl('/').'?uamfiletype=attachment&uamgetfile='.$url;
1044 }
1045 }
1046 }
1047
1048 return $url;
1049 }
1050
1051 /**
1052 * Caches the urls for the post for a later lookup.
1053 *
1054 * @param string $url The url of the post.
1055 * @param object $post The post object.
1056 *
1057 * @return string
1058 */
1059 public function cachePostLinks($url, $post)
1060 {
1061 $postUrls = (array)$this->cache->getFromCache(self::POST_URL_CACHE_KEY);
1062 $postUrls[$url] = $post->ID;
1063 $this->cache->addToCache(self::POST_URL_CACHE_KEY, $postUrls);
1064 return $url;
1065 }
1066
1067 /**
1068 * Filter for Yoast SEO Plugin
1069 *
1070 * Hides the url from the site map if the user has no access
1071 *
1072 * @param string $url The url to check
1073 * @param string $type The object type
1074 * @param object $object The object
1075 *
1076 * @return false|string
1077 */
1078 public function getWpSeoUrl($url, $type, $object)
1079 {
1080 return ($this->accessHandler->checkObjectAccess($type, $object->ID) === true) ? $url : false;
1081 }
1082 }
1083