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

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