PluginProbe
User Access Manager / 2.0.7
User Access Manager v2.0.7
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.7, at src/UserAccessManager/Controller/FrontendController.php

1,081 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 }
306
307 return $showPosts;
308 }
309
310 /**
311 * The function for the get_pages filter.
312 *
313 * @param \WP_Post[] $rawPages The pages.
314 *
315 * @return array
316 */
317 public function showPages($rawPages = [])
318 {
319 $showPages = [];
320
321 foreach ($rawPages as $rawPage) {
322 $page = $this->getPost($rawPage);
323
324 if ($page !== false) {
325 $page = $this->processPost($page);
326
327 if ($page !== null) {
328 $showPages[] = $page;
329 }
330 } else {
331 $showPages[] = $rawPage;
332 }
333 }
334
335 $rawPages = $showPages;
336
337 return $rawPages;
338 }
339
340 /**
341 * Needed to prevent the form against the auto <br>s of wordpress
342 *
343 * @param string $content
344 *
345 * @return string
346 */
347 public function showContent($content)
348 {
349 return (string)str_replace('[LOGIN_FORM]', $this->getLoginFormHtml(), $content);
350 }
351
352 /**
353 * The function for the posts_where_paged filter.
354 *
355 * @param string $query The where sql statement.
356 *
357 * @return string
358 */
359 public function showPostSql($query)
360 {
361 $excludedPosts = $this->accessHandler->getExcludedPosts();
362
363 if (count($excludedPosts) > 0) {
364 $excludedPostsStr = implode(', ', $excludedPosts);
365 $query .= " AND {$this->database->getPostsTable()}.ID NOT IN ($excludedPostsStr) ";
366 }
367
368 return $query;
369 }
370
371 /**
372 * Function for the wp_count_posts filter.
373 *
374 * @param \stdClass $counts
375 * @param string $type
376 * @param string $perm
377 *
378 * @return \stdClass
379 */
380 public function showPostCount($counts, $type, $perm)
381 {
382 $cachedCounts = $this->cache->getFromCache(self::POST_COUNTS_CACHE_KEY);
383
384 if ($cachedCounts === null) {
385 $excludedPosts = $this->accessHandler->getExcludedPosts();
386
387 if (count($excludedPosts) > 0) {
388 $excludedPosts = implode('\', \'', $excludedPosts);
389
390 $query = "SELECT post_status, COUNT(*) AS num_posts
391 FROM {$this->database->getPostsTable()}
392 WHERE post_type = %s
393 AND ID NOT IN ('{$excludedPosts}')";
394
395 if ('readable' === $perm && $this->wordpress->isUserLoggedIn() === true) {
396 $postTypeObject = $this->wordpress->getPostTypeObject($type);
397
398 if ($this->wordpress->currentUserCan($postTypeObject->cap->read_private_posts) === false) {
399 $query .= $this->database->prepare(
400 ' AND (post_status != \'private\' OR (post_author = %d AND post_status = \'private\'))',
401 $this->wordpress->getCurrentUser()->ID
402 );
403 }
404 }
405
406 $query .= ' GROUP BY post_status';
407
408 $results = (array)$this->database->getResults(
409 $this->database->prepare($query, $type),
410 ARRAY_A
411 );
412
413 foreach ($results as $result) {
414 if (isset($counts->{$result['post_status']})) {
415 $counts->{$result['post_status']} = $result['num_posts'];
416 }
417 }
418 }
419
420 $cachedCounts = $counts;
421 $this->cache->addToCache(self::POST_COUNTS_CACHE_KEY, $cachedCounts);
422 }
423
424 return $cachedCounts;
425 }
426
427 /**
428 * Sets the excluded terms as argument.
429 *
430 * @param array $arguments
431 *
432 * @return array
433 */
434 public function getTermArguments(array $arguments)
435 {
436 $exclude = (isset($arguments['exclude']) === true) ?
437 $this->wordpress->parseIdList($arguments['exclude']) : [];
438 $arguments['exclude'] = array_merge($exclude, $this->accessHandler->getExcludedTerms());
439 $arguments['exclude'] = array_unique($arguments['exclude']);
440
441 return $arguments;
442 }
443
444 /**
445 * The function for the comments_array filter.
446 *
447 * @param \WP_Comment[] $comments The comments.
448 *
449 * @return array
450 */
451 public function showComment($comments = [])
452 {
453 $showComments = [];
454
455 foreach ($comments as $comment) {
456 $post = $this->objectHandler->getPost($comment->comment_post_ID);
457
458 if ($post !== false
459 && $this->accessHandler->checkObjectAccess($post->post_type, $post->ID) === false
460 ) {
461 if ($this->config->hidePostTypeComments($post->post_type) === true
462 || $this->config->hidePostType($post->post_type) === true
463 || $this->config->atAdminPanel() === true
464 ) {
465 continue;
466 }
467
468 $comment->comment_content = $this->config->getPostTypeCommentContent($post->post_type);
469 }
470
471 $showComments[] = $comment;
472 }
473
474 return $showComments;
475 }
476
477 /**
478 * The function for the get_ancestors filter.
479 *
480 * @param array $ancestors
481 * @param int $objectId
482 * @param string $objectType
483 *
484 * @return array
485 */
486 public function showAncestors($ancestors, $objectId, $objectType)
487 {
488 if ($this->config->lockRecursive() === true
489 && $this->accessHandler->checkObjectAccess($objectType, $objectId) === false
490 ) {
491 return [];
492 }
493
494 foreach ($ancestors as $key => $ancestorId) {
495 if ($this->accessHandler->checkObjectAccess($objectType, $ancestorId) === false) {
496 unset($ancestors[$key]);
497 }
498 }
499
500 return $ancestors;
501 }
502
503 /**
504 * The function for the get_previous_post_where and
505 * the get_next_post_where filter.
506 *
507 * @param string $query The current sql string.
508 *
509 * @return string
510 */
511 public function showNextPreviousPost($query)
512 {
513 $excludedPosts = $this->accessHandler->getExcludedPosts();
514
515 if (count($excludedPosts) > 0) {
516 $excludedPosts = implode(', ', $excludedPosts);
517 $query .= " AND p.ID NOT IN ({$excludedPosts}) ";
518 }
519
520 return $query;
521 }
522
523 /**
524 * Returns the post count for the term.
525 *
526 * @param string $termType
527 * @param int $termId
528 *
529 * @return int
530 */
531 private function getVisibleElementsCount($termType, $termId)
532 {
533 $count = 0;
534
535 $fullTerms = [$termId => $termType];
536 $termTreeMap = $this->objectHandler->getTermTreeMap();
537
538 if (isset($termTreeMap[ObjectHandler::TREE_MAP_CHILDREN][$termType]) === true
539 && isset($termTreeMap[ObjectHandler::TREE_MAP_CHILDREN][$termType][$termId]) === true
540 ) {
541 $fullTerms += $termTreeMap[ObjectHandler::TREE_MAP_CHILDREN][$termType][$termId];
542 }
543
544 $posts = [];
545 $termPostMap = $this->objectHandler->getTermPostMap();
546
547 foreach ($fullTerms as $fullTermId => $fullTermType) {
548 if (isset($termPostMap[$fullTermId]) === true) {
549 $posts += $termPostMap[$fullTermId];
550 }
551 }
552
553 foreach ($posts as $postId => $postType) {
554 if ($this->config->hidePostType($postType) === false
555 || $this->accessHandler->checkObjectAccess(ObjectHandler::GENERAL_POST_OBJECT_TYPE, $postId) === true
556 ) {
557 $count++;
558 }
559 }
560
561 return $count;
562 }
563
564 /**
565 * Modifies the content of the term by the given settings.
566 *
567 * @param \WP_Term $term The current term.
568 * @param bool $isEmpty
569 *
570 * @return mixed
571 */
572 private function processTerm($term, &$isEmpty = null)
573 {
574 $isEmpty = false;
575
576 if (($term instanceof \WP_Term) === false) {
577 return $term;
578 }
579
580 if ($this->accessHandler->checkObjectAccess($term->taxonomy, $term->term_id) === false) {
581 return null;
582 }
583
584 $term->name .= $this->adminOutput($term->taxonomy, $term->term_id, $term->name);
585 $term->count = $this->getVisibleElementsCount($term->taxonomy, $term->term_id);
586
587 //For categories
588 if ($term->count <= 0
589 && $this->config->atAdminPanel() === false
590 && $this->config->hideEmptyTaxonomy($term->taxonomy) === true
591 ) {
592 $isEmpty = true;
593 }
594
595 if ($this->config->lockRecursive() === false) {
596 $currentTerm = $term;
597
598 while ($currentTerm->parent != 0) {
599 $currentTerm = $this->objectHandler->getTerm($currentTerm->parent);
600
601 if ($currentTerm === false) {
602 break;
603 }
604
605 $access = $this->accessHandler->checkObjectAccess(
606 $currentTerm->taxonomy,
607 $currentTerm->term_id
608 );
609
610 if ($access === true) {
611 $term->parent = $currentTerm->term_id;
612 break;
613 }
614 }
615 }
616
617 return $term;
618 }
619
620 /**
621 * The function for the get_term filter.
622 *
623 * @param \WP_Term $term
624 *
625 * @return null|object
626 */
627 public function showTerm($term)
628 {
629 return $this->processTerm($term);
630 }
631
632 /**
633 * The function for the get_terms filter.
634 *
635 * @param array $terms The terms.
636 *
637 * @return array
638 */
639 public function showTerms($terms = [])
640 {
641 foreach ($terms as $key => $term) {
642 $isNumeric = (is_numeric($term) === true);
643
644 if ($isNumeric === true) {
645 if ((int)$term === 0) {
646 unset($terms[$key]);
647 continue;
648 }
649
650 $term = $this->objectHandler->getTerm($term);
651 }
652
653 if (($term instanceof \WP_Term) === false) {
654 continue;
655 }
656
657 $term = $this->processTerm($term, $isEmpty);
658
659 if ($term !== null && $isEmpty === false) {
660 $terms[$key] = ($isNumeric === true) ? $term->term_id : $term;
661 } else {
662 unset($terms[$key]);
663 }
664 }
665
666 return $terms;
667 }
668
669 /**
670 * The function for the wp_get_nav_menu_items filter.
671 *
672 * @param array $items The menu item.
673 *
674 * @return array
675 */
676 public function showCustomMenu($items)
677 {
678 $showItems = [];
679
680 foreach ($items as $key => $item) {
681 $item->title .= $this->adminOutput($item->object, $item->object_id, $item->title);
682
683 if ($this->objectHandler->isPostType($item->object) === true) {
684 if ($this->accessHandler->checkObjectAccess($item->object, $item->object_id) === false) {
685 if ($this->config->hidePostType($item->object) === true
686 || $this->config->atAdminPanel() === true
687 ) {
688 continue;
689 }
690
691 if ($this->config->hidePostTypeTitle($item->object) === true) {
692 $item->title = $this->config->getPostTypeTitle($item->object);
693 }
694 }
695
696 $showItems[$key] = $item;
697 } elseif ($this->objectHandler->isTaxonomy($item->object) === true) {
698 $term = $this->objectHandler->getTerm($item->object_id);
699
700 if ($term !== false) {
701 $term = $this->processTerm($term, $isEmpty);
702
703 if ($term !== null && $isEmpty === false) {
704 $showItems[$key] = $item;
705 }
706 }
707 } else {
708 $showItems[$key] = $item;
709 }
710 }
711
712 return $showItems;
713 }
714
715 /**
716 * The function for the edit_post_link filter.
717 *
718 * @param string $link The edit link.
719 * @param integer $postId The _iId of the post.
720 *
721 * @return string
722 */
723 public function showGroupMembership($link, $postId)
724 {
725 $userGroups = $this->accessHandler->getFilteredUserGroupsForObject(
726 ObjectHandler::GENERAL_POST_OBJECT_TYPE,
727 $postId
728 );
729
730 if (count($userGroups) > 0) {
731 $escapedGroups = array_map(
732 function (UserGroup $group) {
733 return htmlentities($group->getName());
734 },
735 $userGroups
736 );
737
738 $link .= ' | '.TXT_UAM_ASSIGNED_GROUPS.': ';
739 $link .= implode(', ', $escapedGroups);
740 }
741
742 return $link;
743 }
744
745 /**
746 * Checks if we allowed show the login form.
747 *
748 * @return bool
749 */
750 public function showLoginForm()
751 {
752 return $this->wordpress->isSingle() === true || $this->wordpress->isPage() === true;
753 }
754
755 /**
756 * Returns the login url.
757 *
758 * @var array $parameters
759 *
760 * @return mixed
761 */
762 public function getLoginUrl(array $parameters = [])
763 {
764 $loginUrl = $this->wordpress->getBlogInfo('wpurl').'/wp-login.php';
765 $loginUrl .= (count($parameters) > 0) ? '?'.http_build_query($parameters) : '';
766 return $this->wordpress->applyFilters('uam_login_form_url', $loginUrl, $parameters);
767 }
768
769 /**
770 * Returns the login redirect url.
771 *
772 * @return mixed
773 */
774 public function getRedirectLoginUrl()
775 {
776 $loginUrl = $this->wordpress->getBlogInfo('wpurl')
777 .'/wp-login.php?redirect_to='.urlencode($_SERVER['REQUEST_URI']);
778 return $this->wordpress->applyFilters('uam_login_url', $loginUrl);
779 }
780
781 /**
782 * Returns the user login name.
783 *
784 * @return string
785 */
786 public function getUserLogin()
787 {
788 $userLogin = $this->getRequestParameter('log');
789 return $this->wordpress->escHtml(stripslashes($userLogin));
790 }
791
792
793 /*
794 * Functions for the redirection and files.
795 */
796
797 /**
798 * Returns the post by the given url.
799 *
800 * @param string $url The url of the post(attachment).
801 *
802 * @return int
803 */
804 public function getPostIdByUrl($url)
805 {
806 $postUrls = (array)$this->cache->getFromCache(self::POST_URL_CACHE_KEY);
807
808 if (isset($postUrls[$url]) === true) {
809 return $postUrls[$url];
810 }
811
812 $postUrls[$url] = null;
813
814 //Filter edit string
815 $newUrlPieces = preg_split('/-e[0-9]{1,}/', $url);
816 $newUrl = (count($newUrlPieces) === 2) ? $newUrlPieces[0].$newUrlPieces[1] : $newUrlPieces[0];
817
818 //Filter size
819 $newUrlPieces = preg_split('/-[0-9]{1,}x[0-9]{1,}(_[a-z])?/', $newUrl);
820 $newUrl = (count($newUrlPieces) === 2) ? $newUrlPieces[0].$newUrlPieces[1] : $newUrlPieces[0];
821 $newUrl = preg_replace('/\-pdf\.jpg$/', '.pdf', $newUrl);
822
823 $query = $this->database->prepare(
824 "SELECT ID
825 FROM {$this->database->getPostsTable()}
826 WHERE guid = '%s'
827 LIMIT 1",
828 $newUrl
829 );
830
831 $dbPost = $this->database->getRow($query);
832
833 if ($dbPost !== null) {
834 $postUrls[$url] = $dbPost->ID;
835 $this->cache->addToCache(self::POST_URL_CACHE_KEY, $postUrls);
836 }
837
838 return $postUrls[$url];
839 }
840
841 /**
842 * Returns the file object by the given type and url.
843 *
844 * @param string $objectType The type of the requested file.
845 * @param string $objectUrl The file url.
846 *
847 * @return null|FileObject
848 */
849 private function getFileSettingsByType($objectType, $objectUrl)
850 {
851 $fileObject = null;
852
853 if ($objectType === ObjectHandler::ATTACHMENT_OBJECT_TYPE) {
854 $uploadDirs = $this->wordpress->getUploadDir();
855 $uploadDir = str_replace(ABSPATH, '/', $uploadDirs['basedir']);
856 $regex = '/.*'.str_replace('/', '\/', $uploadDir).'\//i';
857 $cleanObjectUrl = preg_replace($regex, '', $objectUrl);
858 $uploadUrl = str_replace('/files', $uploadDir, $uploadDirs['baseurl']);
859 $objectUrl = rtrim($uploadUrl, '/').'/'.ltrim($cleanObjectUrl, '/');
860
861 $post = $this->objectHandler->getPost($this->getPostIdByUrl($objectUrl));
862
863 if ($post !== false
864 && $post->post_type === ObjectHandler::ATTACHMENT_OBJECT_TYPE
865 ) {
866 $multiPath = str_replace('/files', $uploadDir, $uploadDirs['baseurl']);
867
868 $fileObject = $this->fileObjectFactory->createFileObject(
869 $post->ID,
870 $objectType,
871 $uploadDirs['basedir'].str_replace($multiPath, '', $objectUrl),
872 $this->wordpress->attachmentIsImage($post->ID)
873 );
874 }
875 } else {
876 $extraParameter = $this->getRequestParameter('uamextra');
877
878 $fileObject = $this->wordpress->applyFilters(
879 'uam_get_file_settings_by_type',
880 $fileObject,
881 $objectType,
882 $objectUrl,
883 $extraParameter
884 );
885 }
886
887 return $fileObject;
888 }
889
890 /**
891 * Delivers the content of the requested file.
892 *
893 * @param string $objectType The type of the requested file.
894 * @param string $objectUrl The file url.
895 */
896 public function getFile($objectType, $objectUrl)
897 {
898 $fileObject = $this->getFileSettingsByType($objectType, $objectUrl);
899
900 if ($fileObject === null) {
901 return;
902 }
903
904 if ($this->accessHandler->checkObjectAccess($fileObject->getType(), $fileObject->getId()) === true) {
905 $file = $fileObject->getFile();
906 } elseif ($fileObject->isImage() === true) {
907 $realPath = $this->config->getRealPath();
908 $file = $realPath.'assets/gfx/noAccessPic.png';
909 } else {
910 $this->wordpress->wpDie(TXT_UAM_NO_RIGHTS_MESSAGE, TXT_UAM_NO_RIGHTS_TITLE, ['response' => 403]);
911 return;
912 }
913
914 $this->fileHandler->getFile($file, $fileObject->isImage());
915 }
916
917 /**
918 * Redirects the user to his destination.
919 *
920 * @param bool $checkPosts
921 */
922 public function redirectUser($checkPosts = true)
923 {
924 if ($checkPosts === true) {
925 $posts = (array)$this->wordpress->getWpQuery()->get_posts();
926
927 foreach ($posts as $post) {
928 if ($this->accessHandler->checkObjectAccess($post->post_type, $post->ID)) {
929 return;
930 }
931 }
932 }
933
934 $permalink = null;
935 $redirect = $this->config->getRedirect();
936
937 if ($redirect === 'custom_page') {
938 $redirectCustomPage = $this->config->getRedirectCustomPage();
939 $post = $this->objectHandler->getPost($redirectCustomPage);
940 $url = null;
941
942 if ($post !== false) {
943 $url = $post->guid;
944 $permalink = $this->wordpress->getPageLink($post);
945 }
946 } elseif ($redirect === 'custom_url') {
947 $url = $this->config->getRedirectCustomUrl();
948 } else {
949 $url = $this->wordpress->getHomeUrl('/');
950 }
951
952 $currentUrl = $this->util->getCurrentUrl();
953
954 if ($url !== null && $url !== $currentUrl && $permalink !== $currentUrl) {
955 $this->wordpress->wpRedirect($url);
956 return;
957 }
958 }
959
960 /**
961 * Redirects to a page or to content.
962 *
963 * @param string $headers The headers which are given from wordpress.
964 * @param object $pageParams The params of the current page.
965 *
966 * @return string
967 */
968 public function redirect($headers, $pageParams)
969 {
970 $fileUrl = $this->getRequestParameter('uamgetfile');
971 $fileType = $this->getRequestParameter('uamfiletype');
972
973 if ($fileUrl !== null && $fileType !== null) {
974 $this->getFile($fileType, $fileUrl);
975 } elseif ($this->config->atAdminPanel() === false
976 && $this->config->getRedirect() !== 'false'
977 ) {
978 $objectType = null;
979 $objectId = null;
980
981 if (isset($pageParams->query_vars['p']) === true) {
982 $objectType = ObjectHandler::GENERAL_POST_OBJECT_TYPE;
983 $objectId = $pageParams->query_vars['p'];
984 } elseif (isset($pageParams->query_vars['page_id']) === true) {
985 $objectType = ObjectHandler::GENERAL_POST_OBJECT_TYPE;
986 $objectId = $pageParams->query_vars['page_id'];
987 } elseif (isset($pageParams->query_vars['cat_id']) === true) {
988 $objectType = ObjectHandler::GENERAL_TERM_OBJECT_TYPE;
989 $objectId = $pageParams->query_vars['cat_id'];
990 } elseif (isset($pageParams->query_vars['name']) === true) {
991 $postableTypes = implode('\',\'', $this->objectHandler->getPostTypes());
992
993 $query = $this->database->prepare(
994 "SELECT ID
995 FROM {$this->database->getPostsTable()}
996 WHERE post_name = %s
997 AND post_type IN ('{$postableTypes}')",
998 $pageParams->query_vars['name']
999 );
1000
1001 $objectType = ObjectHandler::GENERAL_POST_OBJECT_TYPE;
1002 $objectId = (int)$this->database->getVariable($query);
1003 } elseif (isset($pageParams->query_vars['pagename']) === true) {
1004 $object = $this->wordpress->getPageByPath($pageParams->query_vars['pagename']);
1005
1006 if ($object !== null) {
1007 $objectType = $object->post_type;
1008 $objectId = $object->ID;
1009 }
1010 }
1011
1012 if ($this->accessHandler->checkObjectAccess($objectType, $objectId) === false) {
1013 $this->redirectUser(false);
1014 }
1015 }
1016
1017 return $headers;
1018 }
1019
1020 /**
1021 * Returns the url for a locked file.
1022 *
1023 * @param string $url The base url.
1024 * @param integer $id The _iId of the file.
1025 *
1026 * @return string
1027 */
1028 public function getFileUrl($url, $id)
1029 {
1030 if ($this->config->isPermalinksActive() === false && $this->config->lockFile() === true) {
1031 $post = $this->objectHandler->getPost($id);
1032
1033 if ($post !== null) {
1034 $type = explode('/', $post->post_mime_type);
1035 $type = (isset($type[1]) === true) ? $type[1] : $type[0];
1036
1037 $lockedFileTypes = $this->config->getLockedFileTypes();
1038 $fileTypes = explode(',', $lockedFileTypes);
1039
1040 if ($lockedFileTypes === 'all' || in_array($type, $fileTypes) === true) {
1041 $url = $this->wordpress->getHomeUrl('/').'?uamfiletype=attachment&uamgetfile='.$url;
1042 }
1043 }
1044 }
1045
1046 return $url;
1047 }
1048
1049 /**
1050 * Caches the urls for the post for a later lookup.
1051 *
1052 * @param string $url The url of the post.
1053 * @param object $post The post object.
1054 *
1055 * @return string
1056 */
1057 public function cachePostLinks($url, $post)
1058 {
1059 $postUrls = (array)$this->cache->getFromCache(self::POST_URL_CACHE_KEY);
1060 $postUrls[$url] = $post->ID;
1061 $this->cache->addToCache(self::POST_URL_CACHE_KEY, $postUrls);
1062 return $url;
1063 }
1064
1065 /**
1066 * Filter for Yoast SEO Plugin
1067 *
1068 * Hides the url from the site map if the user has no access
1069 *
1070 * @param string $url The url to check
1071 * @param string $type The object type
1072 * @param object $object The object
1073 *
1074 * @return false|string
1075 */
1076 public function getWpSeoUrl($url, $type, $object)
1077 {
1078 return ($this->accessHandler->checkObjectAccess($type, $object->ID) === true) ? $url : false;
1079 }
1080 }
1081