PluginProbe
User Access Manager / 1.2.7.6
User Access Manager v1.2.7.6
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 / class / UserAccessManager.php

UserAccessManager.php in User Access Manager 1.2.7.6, at class/UserAccessManager.php

2,373 lines 71.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * UserAccessManager.php
4 *
5 * The UserAccessManager class file.
6 *
7 * PHP versions 5
8 *
9 * @category UserAccessManager
10 * @package UserAccessManager
11 * @author Alexander Schneider <alexanderschneider85@googlemail.com>
12 * @copyright 2008-2016 Alexander Schneider
13 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
14 * @version SVN: $Id$
15 * @link http://wordpress.org/extend/plugins/user-access-manager/
16 */
17
18 /**
19 * The user user access manager class.
20 *
21 * @category UserAccessManager
22 * @package UserAccessManager
23 * @author Alexander Schneider <alexanderschneider85@gmail.com>
24 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
25 * @link http://wordpress.org/extend/plugins/user-access-manager/
26 */
27 class UserAccessManager
28 {
29 const USER_OBJECT_TYPE = 'user';
30 const POST_OBJECT_TYPE = 'post';
31 const PAGE_OBJECT_TYPE = 'page';
32 const TERM_OBJECT_TYPE = 'term';
33 const ROLE_OBJECT_TYPE = 'role';
34 const ATTACHMENT_OBJECT_TYPE = 'attachment';
35
36 protected $_oConfig = null;
37 protected $_blAtAdminPanel = false;
38 protected $_sUamVersion = '1.2.7.6';
39 protected $_sUamDbVersion = '1.4';
40 protected $_oAccessHandler = null;
41 protected $_aPostUrls = array();
42 protected $_aMimeTypes = null;
43 protected $_aCache = array();
44 protected $_aUsers = array();
45 protected $_aPosts = array();
46 protected $_aTerms = array();
47 protected $_aWpOptions = array();
48 protected $_aTermPostMap = array();
49 protected $_aPostTypes = null;
50 protected $_aTaxonomies = null;
51
52 /**
53 * Constructor.
54 */
55 public function __construct()
56 {
57 do_action('uam_init', $this);
58 }
59
60 /**
61 * Flushes the cache.
62 */
63 public function flushCache()
64 {
65 $this->_aCache = array();
66 }
67
68 /**
69 * Returns the database.
70 *
71 * @return wpdb
72 */
73 public function getDatabase()
74 {
75 global $wpdb;
76 return $wpdb;
77 }
78
79 /**
80 * Returns all post types.
81 *
82 * @return array
83 */
84 public function getPostTypes()
85 {
86 if ($this->_aPostTypes === null) {
87 $this->_aPostTypes = get_post_types(array('publicly_queryable' => true));
88 }
89
90 return $this->_aPostTypes;
91 }
92
93 /**
94 * Returns the taxonomies.
95 *
96 * @return array
97 */
98 public function getTaxonomies()
99 {
100 if ($this->_aTaxonomies === null) {
101 $this->_aTaxonomies = get_taxonomies();
102 }
103
104 return $this->_aTaxonomies;
105 }
106
107 /**
108 * Adds the variable to the cache.
109 *
110 * @param string $sKey The cache key
111 * @param mixed $mValue The value.
112 */
113 public function addToCache($sKey, $mValue)
114 {
115 $this->_aCache[$sKey] = $mValue;
116 }
117
118 /**
119 * Returns a value from the cache by the given key.
120 *
121 * @param string $sKey
122 *
123 * @return mixed
124 */
125 public function getFromCache($sKey)
126 {
127 if (isset($this->_aCache[$sKey])) {
128 return $this->_aCache[$sKey];
129 }
130
131 return null;
132 }
133
134 /**
135 * Returns a user.
136 *
137 * @param string $sId The user id.
138 *
139 * @return mixed
140 */
141 public function getUser($sId)
142 {
143 if (!isset($this->_aUsers[$sId])) {
144 $this->_aUsers[$sId] = get_userdata($sId);
145 }
146
147 return $this->_aUsers[$sId];
148 }
149
150 /**
151 * Returns a post.
152 *
153 * @param string $sId The post id.
154 *
155 * @return mixed
156 */
157 public function getPost($sId)
158 {
159 if (!isset($this->_aPosts[$sId])) {
160 $this->_aPosts[$sId] = get_post($sId);
161 }
162
163 return $this->_aPosts[$sId];
164 }
165
166 /**
167 * Returns a term.
168 *
169 * @param string $sId The term id.
170 * @param string $sTaxonomy The taxonomy.
171 *
172 * @return mixed
173 */
174 public function getTerm($sId, $sTaxonomy = '')
175 {
176 if (!isset($this->_aTerms[$sId])) {
177 $this->_aTerms[$sId] = get_term($sId, $sTaxonomy);
178 }
179
180 return $this->_aTerms[$sId];
181 }
182
183 /**
184 * Returns all blog of the network.
185 *
186 * @return array()
187 */
188 protected function _getBlogIds()
189 {
190 $oDatabase = $this->getDatabase();
191 $aBlogIds = array();
192
193 if (is_multisite()) {
194 $aBlogIds = $oDatabase->get_col(
195 "SELECT blog_id
196 FROM ".$oDatabase->blogs
197 );
198 }
199
200 return $aBlogIds;
201 }
202
203 /**
204 * Installs the user access manager.
205 */
206 public function install()
207 {
208 $oDatabase = $this->getDatabase();
209 $aBlogIds = $this->_getBlogIds();
210
211 if (isset($_GET['networkwide'])
212 && ((int)$_GET['networkwide'] === 1)
213 ) {
214 $iCurrentBlogId = $oDatabase->blogid;
215
216 foreach ($aBlogIds as $iBlogId) {
217 switch_to_blog($iBlogId);
218 $this->_installUam();
219 }
220
221 switch_to_blog($iCurrentBlogId);
222
223 return null;
224 }
225
226 $this->_installUam();
227 }
228
229 /**
230 * Creates the needed tables at the database and adds the options
231 */
232 protected function _installUam()
233 {
234 $oDatabase = $this->getDatabase();
235 include_once ABSPATH.'wp-admin/includes/upgrade.php';
236
237 $sCharsetCollate = $this->_getCharset();
238
239 $sDbAccessGroupTable = $oDatabase->prefix.'uam_accessgroups';
240
241 $sDbUserGroup = $oDatabase->get_var(
242 "SHOW TABLES
243 LIKE '".$sDbAccessGroupTable."'"
244 );
245
246 if ($sDbUserGroup != $sDbAccessGroupTable) {
247 dbDelta(
248 "CREATE TABLE ".$sDbAccessGroupTable." (
249 ID int(11) NOT NULL auto_increment,
250 groupname tinytext NOT NULL,
251 groupdesc text NOT NULL,
252 read_access tinytext NOT NULL,
253 write_access tinytext NOT NULL,
254 ip_range mediumtext NULL,
255 PRIMARY KEY (ID)
256 ) $sCharsetCollate;"
257 );
258 }
259
260 $sDbAccessGroupToObjectTable = $oDatabase->prefix.'uam_accessgroup_to_object';
261
262 $sDbAccessGroupToObject = $oDatabase->get_var(
263 "SHOW TABLES
264 LIKE '".$sDbAccessGroupToObjectTable."'"
265 );
266
267 if ($sDbAccessGroupToObject != $sDbAccessGroupToObjectTable) {
268 dbDelta(
269 "CREATE TABLE " . $sDbAccessGroupToObjectTable . " (
270 object_id VARCHAR(64) NOT NULL,
271 object_type varchar(64) NOT NULL,
272 group_id int(11) NOT NULL,
273 PRIMARY KEY (object_id,object_type,group_id)
274 ) $sCharsetCollate;"
275 );
276 }
277
278 add_option("uam_db_version", $this->_sUamDbVersion);
279 }
280
281 /**
282 * Checks if a database update is necessary.
283 *
284 * @return boolean
285 */
286 public function isDatabaseUpdateNecessary()
287 {
288 $oDatabase = $this->getDatabase();
289 $aBlogIds = $this->_getBlogIds();
290
291 if ($aBlogIds !== array()
292 && is_super_admin()
293 ) {
294 foreach ($aBlogIds as $iBlogId) {
295 $sTable = $oDatabase->get_blog_prefix($iBlogId).'options';
296 $sSelect = "SELECT option_value FROM {$sTable} WHERE option_name = %s LIMIT 1";
297 $sSelect = $oDatabase->prepare($sSelect, 'uam_db_version');
298 $sCurrentDbVersion = $oDatabase->get_var($sSelect);
299
300 if (version_compare($sCurrentDbVersion, $this->_sUamDbVersion, '<')) {
301 return true;
302 }
303 }
304 }
305
306 $sCurrentDbVersion = get_option('uam_db_version');
307 return version_compare($sCurrentDbVersion, $this->_sUamDbVersion, '<');
308 }
309
310 /**
311 * Updates the user access manager if an old version was installed.
312 *
313 * @param boolean $blNetworkWide If true update network wide
314 */
315 public function update($blNetworkWide)
316 {
317 $oDatabase = $this->getDatabase();
318 $aBlogIds = $this->_getBlogIds();
319
320 if ($blNetworkWide
321 && $aBlogIds !== array()
322 ) {
323 $iCurrentBlogId = $oDatabase->blogid;
324
325 foreach ($aBlogIds as $iBlogId) {
326 switch_to_blog($iBlogId);
327 $this->_installUam();
328 $this->_updateUam();
329 }
330
331 switch_to_blog($iCurrentBlogId);
332 } else {
333 $this->_updateUam();
334 }
335 }
336
337 /**
338 * Updates the user access manager if an old version was installed.
339 */
340 protected function _updateUam()
341 {
342 $oDatabase = $this->getDatabase();
343 $sCurrentDbVersion = get_option('uam_db_version');
344
345 if (empty($sCurrentDbVersion)) {
346 $this->install();
347 }
348
349 if (!get_option('uam_version') || version_compare(get_option('uam_version'), "1.0", '<')) {
350 delete_option('allow_comments_locked');
351 }
352
353 $sDbAccessGroup = $oDatabase->prefix.'uam_accessgroups';
354
355 $sDbUserGroup = $oDatabase->get_var(
356 "SHOW TABLES
357 LIKE '".$sDbAccessGroup."'"
358 );
359
360 if (version_compare($sCurrentDbVersion, $this->_sUamDbVersion, '<')) {
361 $sCharsetCollate = $this->_getCharset();
362
363 if (version_compare($sCurrentDbVersion, "1.0", '<=')) {
364 if ($sDbUserGroup == $sDbAccessGroup) {
365 $oDatabase->query(
366 "ALTER TABLE ".$sDbAccessGroup."
367 ADD read_access TINYTEXT NOT NULL DEFAULT '',
368 ADD write_access TINYTEXT NOT NULL DEFAULT '',
369 ADD ip_range MEDIUMTEXT NULL DEFAULT ''"
370 );
371
372 $oDatabase->query(
373 "UPDATE ".$sDbAccessGroup."
374 SET read_access = 'group',
375 write_access = 'group'"
376 );
377
378 $sDbIpRange = $oDatabase->get_var(
379 "SHOW columns
380 FROM ".$sDbAccessGroup."
381 LIKE 'ip_range'"
382 );
383
384 if ($sDbIpRange != 'ip_range') {
385 $oDatabase->query(
386 "ALTER TABLE ".$sDbAccessGroup."
387 ADD ip_range MEDIUMTEXT NULL DEFAULT ''"
388 );
389 }
390 }
391
392 $sDbAccessGroupToObject = $oDatabase->prefix.'uam_accessgroup_to_object';
393 $sDbAccessGroupToPost = $oDatabase->prefix.'uam_accessgroup_to_post';
394 $sDbAccessGroupToUser = $oDatabase->prefix.'uam_accessgroup_to_user';
395 $sDbAccessGroupToCategory = $oDatabase->prefix.'uam_accessgroup_to_category';
396 $sDbAccessGroupToRole = $oDatabase->prefix.'uam_accessgroup_to_role';
397
398 $oDatabase->query(
399 "ALTER TABLE '{$sDbAccessGroupToObject}'
400 CHANGE 'object_id' 'object_id' VARCHAR(64)
401 ".$sCharsetCollate
402 );
403
404 $aObjectTypes = $this->getAccessHandler()->getObjectTypes();
405
406 foreach ($aObjectTypes as $sObjectType) {
407 $sAddition = '';
408
409 if ($this->getAccessHandler()->isPostableType($sObjectType)) {
410 $sDbIdName = 'post_id';
411 $sDatabase = $sDbAccessGroupToPost.', '.$oDatabase->posts;
412 $sAddition = " WHERE post_id = ID
413 AND post_type = '".$sObjectType."'";
414 } elseif ($sObjectType == 'category') {
415 $sDbIdName = 'category_id';
416 $sDatabase = $sDbAccessGroupToCategory;
417 } elseif ($sObjectType == 'user') {
418 $sDbIdName = 'user_id';
419 $sDatabase = $sDbAccessGroupToUser;
420 } elseif ($sObjectType == 'role') {
421 $sDbIdName = 'role_name';
422 $sDatabase = $sDbAccessGroupToRole;
423 } else {
424 continue;
425 }
426
427 $sFullDatabase = $sDatabase.$sAddition;
428
429 $sSql = "SELECT {$sDbIdName} as id, group_id as groupId
430 FROM {$sFullDatabase}";
431
432 $aDbObjects = $oDatabase->get_results($sSql);
433
434 foreach ($aDbObjects as $oDbObject) {
435 $sSql = "INSERT INTO {$sDbAccessGroupToObject} (
436 group_id,
437 object_id,
438 object_type
439 )
440 VALUES(
441 '{$oDbObject->groupId}',
442 '{$oDbObject->id}',
443 '{$sObjectType}'
444 )";
445
446 $oDatabase->query($sSql);
447 }
448 }
449
450 $oDatabase->query(
451 "DROP TABLE {$sDbAccessGroupToPost},
452 {$sDbAccessGroupToUser},
453 {$sDbAccessGroupToCategory},
454 {$sDbAccessGroupToRole}"
455 );
456 }
457
458 if (version_compare($sCurrentDbVersion, "1.2", '<=')) {
459 $sDbAccessGroupToObject = $oDatabase->prefix.'uam_accessgroup_to_object';
460
461 $sSql = "
462 ALTER TABLE `{$sDbAccessGroupToObject}`
463 CHANGE `object_id` `object_id` VARCHAR(64) NOT NULL,
464 CHANGE `object_type` `object_type` VARCHAR(64) NOT NULL";
465
466 $oDatabase->query($sSql);
467 }
468
469 if (version_compare($sCurrentDbVersion, "1.3", '<=')) {
470 $sDbAccessGroupToObject = $oDatabase->prefix.'uam_accessgroup_to_object';
471 $sTermType = UserAccessManager::TERM_OBJECT_TYPE;
472
473 $sSql = "
474 UPDATE `{$sDbAccessGroupToObject}` AS ag2o
475 SET ag2o.`object_type` = '{$sTermType}'
476 WHERE `object_type` = 'category'";
477
478 $oDatabase->query($sSql);
479 }
480
481 update_option('uam_db_version', $this->_sUamDbVersion);
482 }
483 }
484
485 /**
486 * Clean up wordpress if the plugin will be uninstalled.
487 */
488 public function uninstall()
489 {
490 $oDatabase = $this->getDatabase();
491
492 $oDatabase->query(
493 "DROP TABLE ".DB_ACCESSGROUP.",
494 ".DB_ACCESSGROUP_TO_OBJECT
495 );
496
497 delete_option(UamConfig::ADMIN_OPTIONS_NAME);
498 delete_option('uam_version');
499 delete_option('uam_db_version');
500 $this->deleteFileProtectionFiles();
501 }
502
503 /**
504 * Returns the database charset.
505 *
506 * @return string
507 */
508 protected function _getCharset()
509 {
510 $oDatabase = $this->getDatabase();
511 $sCharsetCollate = '';
512
513 $sMySlqVersion = $oDatabase->get_var("SELECT VERSION() as mysql_version");
514
515 if (version_compare($sMySlqVersion, '4.1.0', '>=')) {
516 if (!empty($oDatabase->charset)) {
517 $sCharsetCollate = "DEFAULT CHARACTER SET $oDatabase->charset";
518 }
519
520 if (!empty($oDatabase->collate)) {
521 $sCharsetCollate.= " COLLATE $oDatabase->collate";
522 }
523 }
524
525 return $sCharsetCollate;
526 }
527
528 /**
529 * Remove the htaccess file if the plugin is deactivated.
530 */
531 public function deactivate()
532 {
533 $this->deleteFileProtectionFiles();
534 }
535
536 /**
537 * Returns the current user.
538 *
539 * @return WP_User
540 */
541 public function getCurrentUser()
542 {
543 if (!function_exists('get_userdata')) {
544 include_once ABSPATH.'wp-includes/pluggable.php';
545 }
546
547 //Force user information
548 return wp_get_current_user();
549 }
550
551 /**
552 * Returns the full supported mine types.
553 *
554 * @return array
555 */
556 protected function _getMimeTypes()
557 {
558 if ($this->_aMimeTypes === null) {
559 $aMimeTypes = get_allowed_mime_types();
560 $aFullMimeTypes = array();
561
562 foreach ($aMimeTypes as $sExtensions => $sMineType) {
563 $aExtension = explode('|', $sExtensions);
564
565 foreach ($aExtension as $sExtension) {
566 $aFullMimeTypes[$sExtension] = $sMineType;
567 }
568 }
569
570 $this->_aMimeTypes = $aFullMimeTypes;
571 }
572
573 return $this->_aMimeTypes;
574 }
575
576 /**
577 * @param string $sFileTypes The file types which should be cleaned up.
578 *
579 * @return string
580 */
581 protected function _cleanUpFileTypesForHtaccess($sFileTypes)
582 {
583 $aValidFileTypes = array();
584 $aFileTypes = explode(',', $sFileTypes);
585 $aMimeTypes = $this->_getMimeTypes();
586
587 foreach ($aFileTypes as $sFileType) {
588 $sCleanFileType = trim($sFileType);
589
590 if (isset($aMimeTypes[$sCleanFileType])) {
591 $aValidFileTypes[$sCleanFileType] = $sCleanFileType;
592 }
593 }
594
595 return implode('|', $aValidFileTypes);
596 }
597
598 /**
599 * Returns true if web server is nginx.
600 *
601 * @return bool
602 */
603 public function isNginx()
604 {
605 global $is_nginx;
606 return $is_nginx;
607 }
608
609 /**
610 * Creates a htaccess file.
611 *
612 * @param string $sDir The destination directory.
613 * @param string $sObjectType The object type.
614 */
615 public function createFileProtection($sDir = null, $sObjectType = null)
616 {
617 $blNginx = $this->isNginx();
618
619 if ($sDir === null) {
620 $aWordpressUploadDir = wp_upload_dir();
621
622 if (empty($aWordpressUploadDir['error'])) {
623 $sDir = $aWordpressUploadDir['basedir'] . "/";
624 }
625 }
626
627 $sFileName = ($blNginx === true) ? "uam.conf" : ".htaccess";
628
629 if ($sDir !== null) {
630 $sFile = "";
631 $sAreaName = "WP-Files";
632 $oConfig = $this->getConfig();
633
634 if (!$this->isPermalinksActive()) {
635 $sFileTypes = null;
636
637 if ($oConfig->getLockedFileTypes() == 'selected') {
638 $sFileTypes = $this->_cleanUpFileTypesForHtaccess($oConfig->getLockedFileTypes());
639 $sFileTypes = "\.(".$sFileTypes.")";
640 } elseif ($blNginx === false && $oConfig->getLockedFileTypes() == 'not_selected') {
641 $sFileTypes = $this->_cleanUpFileTypesForHtaccess($oConfig->getLockedFileTypes());
642 $sFileTypes = "^\.(".$sFileTypes.")";
643 }
644
645 if ($blNginx === true) {
646 $sFile = "location " . str_replace(ABSPATH, '/', $sDir) . " {\n";
647
648 if ($sFileTypes !== null) {
649 $sFile .= "location ~ $sFileTypes {\n";
650 }
651
652 $sFile .= "auth_basic \"" . $sAreaName . "\";" . "\n";
653 $sFile .= "auth_basic_user_file ". $sDir . ".htpasswd;" . "\n";
654 $sFile .= "}\n";
655
656 if ($sFileTypes !== null) {
657 $sFile .= "}\n";
658 }
659 } else {
660 // make .htaccess and .htpasswd
661 $sFile .= "AuthType Basic" . "\n";
662 $sFile .= "AuthName \"" . $sAreaName . "\"" . "\n";
663 $sFile .= "AuthUserFile " . $sDir . ".htpasswd" . "\n";
664 $sFile .= "require valid-user" . "\n";
665
666 if ($sFileTypes !== null) {
667 $sFile = "<FilesMatch '" . $sFileTypes . "'>\n" . $sFile . "</FilesMatch>\n";
668 }
669 }
670
671 $this->createHtpasswd(true);
672 } else {
673 if ($sObjectType === null) {
674 $sObjectType = UserAccessManager::ATTACHMENT_OBJECT_TYPE;
675 }
676
677 if ($blNginx === true) {
678 $sFile = "location " . str_replace(ABSPATH, '/', $sDir) . " {" . "\n";
679 $sFile .= "rewrite ^(.*)$ /index.php?uamfiletype=" . $sObjectType . "&uamgetfile=$1 last;" . "\n";
680 $sFile .= "}" . "\n";
681 } else {
682 $aHomeRoot = parse_url(home_url());
683 $sHomeRoot = (isset($aHomeRoot['path'])) ? trailingslashit($aHomeRoot['path']) : '/';
684
685 $sFile = "<IfModule mod_rewrite.c>\n";
686 $sFile .= "RewriteEngine On\n";
687 $sFile .= "RewriteBase " . $sHomeRoot . "\n";
688 $sFile .= "RewriteRule ^index\.php$ - [L]\n";
689 $sFile .= "RewriteRule (.*) ";
690 $sFile .= $sHomeRoot . "index.php?uamfiletype=" . $sObjectType . "&uamgetfile=$1 [L]\n";
691 $sFile .= "</IfModule>\n";
692 }
693 }
694
695 // save files
696 $sFileWithPath = ($blNginx === true) ? ABSPATH.$sFileName : $sDir.$sFileName;
697
698 $oFileHandler = fopen($sFileWithPath, "w");
699 fwrite($oFileHandler, $sFile);
700 fclose($oFileHandler);
701 }
702 }
703
704 /**
705 * Creates a htpasswd file.
706 *
707 * @param boolean $blCreateNew Force to create new file.
708 * @param string $sDir The destination directory.
709 */
710 public function createHtpasswd($blCreateNew = false, $sDir = null)
711 {
712 $oCurrentUser = $this->getCurrentUser();
713 if (!function_exists('get_userdata')) {
714 include_once ABSPATH.'wp-includes/pluggable.php';
715 }
716
717 $oConfig = $this->getConfig();
718
719 // get url
720 if ($sDir === null) {
721 $aWordpressUploadDir = wp_upload_dir();
722
723 if (empty($aWordpressUploadDir['error'])) {
724 $sDir = $aWordpressUploadDir['basedir'] . "/";
725 }
726 }
727
728 if ($sDir !== null) {
729 $oUserData = $this->getUser($oCurrentUser->ID);
730
731 if (!file_exists($sDir.".htpasswd") || $blCreateNew) {
732 if ($oConfig->getFilePassType() === 'random') {
733 $sPassword = md5($this->getRandomPassword());
734 } else {
735 $sPassword = $oUserData->user_pass;
736 }
737
738 $sUser = $oUserData->user_login;
739
740 // make .htpasswd
741 $sHtpasswdTxt = "$sUser:" . $sPassword . "\n";
742
743 // save file
744 $oFileHandler = fopen($sDir.".htpasswd", "w");
745 fwrite($oFileHandler, $sHtpasswdTxt);
746 fclose($oFileHandler);
747 }
748 }
749 }
750
751 /**
752 * Deletes the htaccess files.
753 *
754 * @param string $sDir The destination directory.
755 */
756 public function deleteFileProtectionFiles($sDir = null)
757 {
758 if ($sDir === null) {
759 $aWordpressUploadDir = wp_upload_dir();
760
761 if (empty($aWordpressUploadDir['error'])) {
762 $sDir = $aWordpressUploadDir['basedir'] . "/";
763 }
764 }
765
766 if ($sDir !== null) {
767 $blNginx = $this->isNginx();
768 $sFileName = ($blNginx === true) ? ABSPATH."uam.conf" : $sDir.".htaccess";
769
770 if (file_exists($sFileName)) {
771 unlink($sFileName);
772 }
773
774 if (file_exists($sDir.".htpasswd")) {
775 unlink($sDir.".htpasswd");
776 }
777 }
778 }
779
780 /**
781 * Generates and returns a random password.
782 *
783 * @return string
784 */
785 public function getRandomPassword()
786 {
787 //create password
788 $aArray = array();
789 $iLength = 16;
790
791 // numbers
792 for ($i = 48; $i < 58; $i++) {
793 $aArray[] = chr($i);
794 }
795
796 // small
797 for ($i = 97; $i < 122; $i++) {
798 $aArray[] = chr($i);
799 }
800
801 // capitals
802 for ($i = 65; $i < 90; $i++) {
803 $aArray[] = chr($i);
804 }
805
806 mt_srand((double)microtime() * 1000000);
807 $sPassword = '';
808
809 for ($i = 1; $i <= $iLength; $i++) {
810 $iRandomNumber = mt_rand(0, count($aArray) - 1);
811 $sPassword .= $aArray[$iRandomNumber];
812 }
813
814 return $sPassword;
815 }
816
817 /**
818 * Returns the current config.
819 *
820 * @return UamConfig
821 */
822 public function getConfig()
823 {
824 if ($this->_oConfig === null) {
825 $this->_oConfig = new UamConfig();
826 }
827
828 return $this->_oConfig;
829 }
830
831 /**
832 * Returns the content of the excluded php file.
833 *
834 * @param string $sFileName The file name
835 * @param integer $iObjectId The _iId if needed.
836 * @param string $sObjectType The object type if needed.
837 *
838 * @return string
839 */
840 public function getIncludeContents($sFileName, $iObjectId = null, $sObjectType = null)
841 {
842 if (is_file($sFileName)) {
843 ob_start();
844 include $sFileName;
845 $sContents = ob_get_contents();
846 ob_end_clean();
847
848 return $sContents;
849 }
850
851 return '';
852 }
853
854 /**
855 * Returns the access handler object.
856 *
857 * @return UamAccessHandler
858 */
859 public function &getAccessHandler()
860 {
861 if ($this->_oAccessHandler == null) {
862 $this->_oAccessHandler = new UamAccessHandler($this);
863 }
864
865 return $this->_oAccessHandler;
866 }
867
868 /**
869 * Returns the current version of the user access manager.
870 *
871 * @return string
872 */
873 public function getVersion()
874 {
875 return $this->_sUamVersion;
876 }
877
878 /**
879 * Returns true if a user is at the admin panel.
880 *
881 * @return boolean
882 */
883 public function atAdminPanel()
884 {
885 return $this->_blAtAdminPanel;
886 }
887
888 /**
889 * Sets the atAdminPanel var to true.
890 */
891 public function setAtAdminPanel()
892 {
893 $this->_blAtAdminPanel = true;
894 }
895
896
897 /*
898 * Helper functions.
899 */
900
901 /**
902 * Checks if a string starts with the given needle.
903 *
904 * @param string $sHaystack The haystack.
905 * @param string $sNeedle The needle.
906 *
907 * @return boolean
908 */
909 public function startsWith($sHaystack, $sNeedle)
910 {
911 return strpos($sHaystack, $sNeedle) === 0;
912 }
913
914
915 /*
916 * Functions for the admin panel content.
917 */
918
919 /**
920 * The function for the wp_print_styles action.
921 */
922 public function addStyles()
923 {
924 wp_enqueue_style(
925 'UserAccessManagerAdmin',
926 UAM_URLPATH . "css/uamAdmin.css",
927 array() ,
928 '1.0',
929 'screen'
930 );
931
932 wp_enqueue_style(
933 'UserAccessManagerLoginForm',
934 UAM_URLPATH . "css/uamLoginForm.css",
935 array() ,
936 '1.0',
937 'screen'
938 );
939 }
940
941 /**
942 * The function for the wp_print_scripts action.
943 */
944 public function addScripts()
945 {
946 wp_enqueue_script(
947 'UserAccessManagerFunctions',
948 UAM_URLPATH . 'js/functions.js',
949 array('jquery')
950 );
951 }
952
953 /**
954 * Prints the admin page.
955 */
956 public function printAdminPage()
957 {
958 if (isset($_GET['page'])) {
959 $sAdminPage = $_GET['page'];
960
961 if ($sAdminPage == 'uam_settings') {
962 include UAM_REALPATH.'tpl/adminSettings.php';
963 } elseif ($sAdminPage == 'uam_usergroup') {
964 include UAM_REALPATH.'tpl/adminGroup.php';
965 } elseif ($sAdminPage == 'uam_setup') {
966 include UAM_REALPATH.'tpl/adminSetup.php';
967 } elseif ($sAdminPage == 'uam_about') {
968 include UAM_REALPATH.'tpl/about.php';
969 }
970 }
971 }
972
973 /**
974 * Shows the error if the user has no rights to edit the content.
975 */
976 public function noRightsToEditContent()
977 {
978 $blNoRights = false;
979
980 if (isset($_GET['post']) && is_numeric($_GET['post'])) {
981 $oPost = $this->getPost($_GET['post']);
982 $blNoRights = !$this->getAccessHandler()->checkObjectAccess($oPost->post_type, $oPost->ID);
983 }
984
985 if (isset($_GET['attachment_id']) && is_numeric($_GET['attachment_id']) && !$blNoRights) {
986 $oPost = $this->getPost($_GET['attachment_id']);
987 $blNoRights = !$this->getAccessHandler()->checkObjectAccess($oPost->post_type, $oPost->ID);
988 }
989
990 if (isset($_GET['tag_ID']) && is_numeric($_GET['tag_ID']) && !$blNoRights) {
991 $blNoRights = !$this->getAccessHandler()->checkObjectAccess(self::TERM_OBJECT_TYPE, $_GET['tag_ID']);
992 }
993
994 if ($blNoRights) {
995 wp_die(TXT_UAM_NO_RIGHTS);
996 }
997 }
998
999 /**
1000 * The function for the wp_dashboard_setup action.
1001 * Removes widgets to which a user should not have access.
1002 */
1003 public function setupAdminDashboard()
1004 {
1005 global $wp_meta_boxes;
1006
1007 if (!$this->getAccessHandler()->checkUserAccess('manage_user_groups')) {
1008 unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
1009 }
1010 }
1011
1012 /**
1013 * The function for the update_option_permalink_structure action.
1014 */
1015 public function updatePermalink()
1016 {
1017 $this->createFileProtection();
1018 }
1019
1020
1021 /*
1022 * Meta functions
1023 */
1024
1025 /**
1026 * Saves the object data to the database.
1027 *
1028 * @param string $sObjectType The object type.
1029 * @param integer $iObjectId The _iId of the object.
1030 * @param UamUserGroup[] $aUserGroups The new usergroups for the object.
1031 */
1032 protected function _saveObjectData($sObjectType, $iObjectId, $aUserGroups = null)
1033 {
1034 $oUamAccessHandler = $this->getAccessHandler();
1035 $oConfig = $this->getConfig();
1036 $aFormData = array();
1037
1038 if (isset($_POST['uam_update_groups'])) {
1039 $aFormData = $_POST;
1040 } elseif (isset($_GET['uam_update_groups'])) {
1041 $aFormData = $_GET;
1042 }
1043
1044 if (isset($aFormData['uam_update_groups'])
1045 && ($oUamAccessHandler->checkUserAccess('manage_user_groups')
1046 || $oConfig->authorsCanAddPostsToGroups() === true)
1047 ) {
1048 if ($aUserGroups === null) {
1049 $aUserGroups = (isset($aFormData['uam_usergroups']) && is_array($aFormData['uam_usergroups']))
1050 ? $aFormData['uam_usergroups'] : array();
1051 }
1052
1053 $aAddUserGroups = array_flip($aUserGroups);
1054 $aRemoveUserGroups = $oUamAccessHandler->getUserGroupsForObject($sObjectType, $iObjectId);
1055 $aUamUserGroups = $oUamAccessHandler->getUserGroups();
1056 $blRemoveOldAssignments = true;
1057
1058 if (isset($aFormData['uam_bulk_type'])) {
1059 $sBulkType = $aFormData['uam_bulk_type'];
1060
1061 if ($sBulkType === 'add') {
1062 $blRemoveOldAssignments = false;
1063 } elseif ($sBulkType === 'remove') {
1064 $aRemoveUserGroups = $aAddUserGroups;
1065 $aAddUserGroups = array();
1066 }
1067 }
1068
1069 foreach ($aUamUserGroups as $sGroupId => $oUamUserGroup) {
1070 if (isset($aRemoveUserGroups[$sGroupId])) {
1071 $oUamUserGroup->removeObject($sObjectType, $iObjectId);
1072 }
1073
1074 if (isset($aAddUserGroups[$sGroupId])) {
1075 $oUamUserGroup->addObject($sObjectType, $iObjectId);
1076 }
1077
1078 $oUamUserGroup->save($blRemoveOldAssignments);
1079 }
1080 }
1081 }
1082
1083 /**
1084 * Removes the object data.
1085 *
1086 * @param string $sObjectType The object type.
1087 * @param int $iId The object id.
1088 */
1089 protected function _removeObjectData($sObjectType, $iId)
1090 {
1091 $oDatabase = $this->getDatabase();
1092
1093 $oDatabase->query(
1094 "DELETE FROM " . DB_ACCESSGROUP_TO_OBJECT . "
1095 WHERE object_id = {$iId}
1096 AND object_type = '{$sObjectType}'"
1097 );
1098 }
1099
1100
1101 /*
1102 * Functions for the post actions.
1103 */
1104
1105 /**
1106 * The function for the manage_posts_columns and
1107 * the manage_pages_columns filter.
1108 *
1109 * @param array $aDefaults The table headers.
1110 *
1111 * @return array
1112 */
1113 public function addPostColumnsHeader($aDefaults)
1114 {
1115 $aDefaults['uam_access'] = __('Access', 'user-access-manager');
1116 return $aDefaults;
1117 }
1118
1119 /**
1120 * The function for the manage_users_custom_column action.
1121 *
1122 * @param string $sColumnName The column name.
1123 * @param integer $iId The id.
1124 */
1125 public function addPostColumn($sColumnName, $iId)
1126 {
1127 if ($sColumnName == 'uam_access') {
1128 $oPost = $this->getPost($iId);
1129 echo $this->getIncludeContents(UAM_REALPATH.'tpl/objectColumn.php', $oPost->ID, $oPost->post_type);
1130 }
1131 }
1132
1133 /**
1134 * The function for the uma_post_access metabox.
1135 *
1136 * @param object $oPost The post.
1137 */
1138 public function editPostContent($oPost)
1139 {
1140 $iObjectId = $oPost->ID;
1141 include UAM_REALPATH.'tpl/postEditForm.php';
1142 }
1143
1144 public function addBulkAction($sColumnName)
1145 {
1146 if ($sColumnName == 'uam_access') {
1147 include UAM_REALPATH.'tpl/bulkEditForm.php';
1148 }
1149 }
1150
1151 /**
1152 * The function for the save_post action.
1153 *
1154 * @param mixed $mPostParam The post _iId or a array of a post.
1155 */
1156 public function savePostData($mPostParam)
1157 {
1158 if (is_array($mPostParam)) {
1159 $oPost = $this->getPost($mPostParam['ID']);
1160 } else {
1161 $oPost = $this->getPost($mPostParam);
1162 }
1163
1164 $iPostId = $oPost->ID;
1165 $sPostType = $oPost->post_type;
1166
1167 if ($sPostType == 'revision') {
1168 $iPostId = $oPost->post_parent;
1169 $oParentPost = $this->getPost($iPostId);
1170 $sPostType = $oParentPost->post_type;
1171 }
1172
1173 $this->_saveObjectData($sPostType, $iPostId);
1174 }
1175
1176 /**
1177 * The function for the attachment_fields_to_save filter.
1178 * We have to use this because the attachment actions work
1179 * not in the way we need.
1180 *
1181 * @param object $oAttachment The attachment id.
1182 *
1183 * @return object
1184 */
1185 public function saveAttachmentData($oAttachment)
1186 {
1187 $this->savePostData($oAttachment['ID']);
1188
1189 return $oAttachment;
1190 }
1191
1192 /**
1193 * The function for the delete_post action.
1194 *
1195 * @param integer $iPostId The post id.
1196 */
1197 public function removePostData($iPostId)
1198 {
1199 $oDatabase = $this->getDatabase();
1200 $oPost = $this->getPost($iPostId);
1201
1202 $oDatabase->query(
1203 "DELETE FROM " . DB_ACCESSGROUP_TO_OBJECT . "
1204 WHERE object_id = '".$iPostId."'
1205 AND object_type = '".$oPost->post_type."'"
1206 );
1207 }
1208
1209 /**
1210 * The function for the media_meta action.
1211 *
1212 * @param string $sMeta The meta.
1213 * @param object $oPost The post.
1214 *
1215 * @return string
1216 */
1217 public function showMediaFile($sMeta = '', $oPost = null)
1218 {
1219 $sContent = $sMeta;
1220 $sContent .= '</td></tr><tr>';
1221 $sContent .= '<th class="label">';
1222 $sContent .= '<label>'.TXT_UAM_SET_UP_USERGROUPS.'</label>';
1223 $sContent .= '</th>';
1224 $sContent .= '<td class="field">';
1225 $sContent .= $this->getIncludeContents(UAM_REALPATH.'tpl/postEditForm.php', $oPost->ID);
1226
1227 return $sContent;
1228 }
1229
1230
1231 /*
1232 * Functions for the user actions.
1233 */
1234
1235 /**
1236 * The function for the manage_users_columns filter.
1237 *
1238 * @param array $aDefaults The table headers.
1239 *
1240 * @return array
1241 */
1242 public function addUserColumnsHeader($aDefaults)
1243 {
1244 $aDefaults['uam_access'] = __('uam user groups');
1245 return $aDefaults;
1246 }
1247
1248 /**
1249 * The function for the manage_users_custom_column action.
1250 *
1251 * @param string $sReturn The normal return value.
1252 * @param string $sColumnName The column name.
1253 * @param integer $iId The id.
1254 *
1255 * @return string|null
1256 */
1257 public function addUserColumn($sReturn, $sColumnName, $iId)
1258 {
1259 if ($sColumnName == 'uam_access') {
1260 return $this->getIncludeContents(UAM_REALPATH.'tpl/userColumn.php', $iId, self::USER_OBJECT_TYPE);
1261 }
1262
1263 return $sReturn;
1264 }
1265
1266 /**
1267 * The function for the edit_user_profile action.
1268 */
1269 public function showUserProfile()
1270 {
1271 echo $this->getIncludeContents(UAM_REALPATH.'tpl/userProfileEditForm.php');
1272 }
1273
1274 /**
1275 * The function for the profile_update action.
1276 *
1277 * @param integer $iUserId The user id.
1278 */
1279 public function saveUserData($iUserId)
1280 {
1281 $this->_saveObjectData(self::USER_OBJECT_TYPE, $iUserId);
1282 }
1283
1284 /**
1285 * The function for the delete_user action.
1286 *
1287 * @param integer $iUserId The user id.
1288 */
1289 public function removeUserData($iUserId)
1290 {
1291 $this->_removeObjectData(self::USER_OBJECT_TYPE, $iUserId);
1292 }
1293
1294
1295 /*
1296 * Functions for the term actions.
1297 */
1298
1299 /**
1300 * The function for the manage_categories_columns filter.
1301 *
1302 * @param array $aDefaults The table headers.
1303 *
1304 * @return array
1305 */
1306 public function addTermColumnsHeader($aDefaults)
1307 {
1308 $aDefaults['uam_access'] = __('Access', 'user-access-manager');
1309 return $aDefaults;
1310 }
1311
1312 /**
1313 * The function for the manage_categories_custom_column action.
1314 *
1315 * @param string $sEmpty An empty string from wordpress? What the hell?!?
1316 * @param string $sColumnName The column name.
1317 * @param integer $iId The id.
1318 *
1319 * @return string|null
1320 */
1321 public function addTermColumn($sEmpty, $sColumnName, $iId)
1322 {
1323 if ($sColumnName == 'uam_access') {
1324 return $this->getIncludeContents(UAM_REALPATH.'tpl/objectColumn.php', $iId, self::TERM_OBJECT_TYPE);
1325 }
1326
1327 return null;
1328 }
1329
1330 /**
1331 * The function for the edit_{term}_form action.
1332 *
1333 * @param object $oTerm The term.
1334 */
1335 public function showTermEditForm($oTerm)
1336 {
1337 include UAM_REALPATH.'tpl/termEditForm.php';
1338 }
1339
1340 /**
1341 * The function for the edit_{term} action.
1342 *
1343 * @param integer $iTermId The term id.
1344 */
1345 public function saveTermData($iTermId)
1346 {
1347 $this->_saveObjectData(self::TERM_OBJECT_TYPE, $iTermId);
1348 }
1349
1350 /**
1351 * The function for the delete_{term} action.
1352 *
1353 * @param integer $iTermId The id of the term.
1354 */
1355 public function removeTermData($iTermId)
1356 {
1357 $this->_removeObjectData(self::TERM_OBJECT_TYPE, $iTermId);
1358 }
1359
1360
1361 /*
1362 * Functions for the pluggable object actions.
1363 */
1364
1365 /**
1366 * The function for the pluggable save action.
1367 *
1368 * @param string $sObjectType The name of the pluggable object.
1369 * @param integer $iObjectId The pluggable object id.
1370 * @param array $aUserGroups The user groups for the object.
1371 */
1372 public function savePlObjectData($sObjectType, $iObjectId, $aUserGroups = null)
1373 {
1374 $this->_saveObjectData($sObjectType, $iObjectId, $aUserGroups);
1375 }
1376
1377 /**
1378 * The function for the pluggable remove action.
1379 *
1380 * @param string $sObjectName The name of the pluggable object.
1381 * @param integer $iObjectId The pluggable object id.
1382 */
1383 public function removePlObjectData($sObjectName, $iObjectId)
1384 {
1385 $this->_removeObjectData($sObjectName, $iObjectId);
1386 }
1387
1388 /**
1389 * Returns the group selection form for pluggable objects.
1390 *
1391 * @param string $sObjectType The object type.
1392 * @param integer $iObjectId The _iId of the object.
1393 * @param string $aGroupsFormName The name of the form which contains the groups.
1394 *
1395 * @return string;
1396 */
1397 public function showPlGroupSelectionForm($sObjectType, $iObjectId, $aGroupsFormName = null)
1398 {
1399 $sFileName = UAM_REALPATH.'tpl/groupSelectionForm.php';
1400 $aUamUserGroups = $this->getAccessHandler()->getUserGroups();
1401 $aUserGroupsForObject = $this->getAccessHandler()->getUserGroupsForObject($sObjectType, $iObjectId);
1402
1403 if (is_file($sFileName)) {
1404 ob_start();
1405 include $sFileName;
1406 $sContents = ob_get_contents();
1407 ob_end_clean();
1408
1409 return $sContents;
1410 }
1411
1412 return '';
1413 }
1414
1415 /**
1416 * Returns the column for a pluggable object.
1417 *
1418 * @param string $sObjectType The object type.
1419 * @param integer $iObjectId The object id.
1420 *
1421 * @return string
1422 */
1423 public function getPlColumn($sObjectType, $iObjectId)
1424 {
1425 return $this->getIncludeContents(UAM_REALPATH.'tpl/objectColumn.php', $iObjectId, $sObjectType);
1426 }
1427
1428
1429 /*
1430 * Functions for the blog content.
1431 */
1432
1433 /**
1434 * Manipulates the wordpress query object to filter content.
1435 *
1436 * @param object $oWpQuery The wordpress query object.
1437 */
1438 public function parseQuery($oWpQuery)
1439 {
1440 $oConfig = $this->getConfig();
1441
1442 if ($oConfig->hidePost() === true) {
1443 $oUamAccessHandler = $this->getAccessHandler();
1444 $aExcludedPosts = $oUamAccessHandler->getExcludedPosts();
1445
1446 if (count($aExcludedPosts) > 0) {
1447 $oWpQuery->query_vars['post__not_in'] = array_merge(
1448 $oWpQuery->query_vars['post__not_in'],
1449 $aExcludedPosts
1450 );
1451 }
1452 }
1453 }
1454
1455 /**
1456 * Modifies the content of the post by the given settings.
1457 *
1458 * @param object $oPost The current post.
1459 *
1460 * @return object|null
1461 */
1462 protected function _getPost($oPost)
1463 {
1464 $oConfig = $this->getConfig();
1465 $oUamAccessHandler = $this->getAccessHandler();
1466
1467 $sPostType = $oPost->post_type;
1468
1469 if ($this->getAccessHandler()->isPostableType($sPostType)
1470 && $sPostType != UserAccessManager::POST_OBJECT_TYPE
1471 && $sPostType != UserAccessManager::PAGE_OBJECT_TYPE
1472 ) {
1473 $sPostType = UserAccessManager::POST_OBJECT_TYPE;
1474 } elseif ($sPostType != UserAccessManager::POST_OBJECT_TYPE
1475 && $sPostType != UserAccessManager::PAGE_OBJECT_TYPE
1476 ) {
1477 return $oPost;
1478 }
1479
1480 if ($oConfig->hideObjectType($sPostType) === true || $this->atAdminPanel()) {
1481 if ($oUamAccessHandler->checkObjectAccess($oPost->post_type, $oPost->ID)) {
1482 $oPost->post_title .= $this->adminOutput($oPost->post_type, $oPost->ID);
1483 return $oPost;
1484 }
1485 } else {
1486 if (!$oUamAccessHandler->checkObjectAccess($oPost->post_type, $oPost->ID)) {
1487 $oPost->isLocked = true;
1488
1489 $sUamPostContent = $oConfig->getObjectTypeContent($sPostType);
1490 $sUamPostContent = str_replace('[LOGIN_FORM]', $this->getLoginBarHtml(), $sUamPostContent);
1491
1492 if ($oConfig->hideObjectTypeTitle($sPostType) === true) {
1493 $oPost->post_title = $oConfig->getObjectTypeTitle($sPostType);
1494 }
1495
1496 if ($oConfig->hideObjectTypeComments($sPostType) === false) {
1497 $oPost->comment_status = 'close';
1498 }
1499
1500 if ($sPostType === 'post'
1501 && $oConfig->showPostContentBeforeMore() === true
1502 && preg_match('/<!--more(.*?)?-->/', $oPost->post_content, $aMatches)
1503 ) {
1504 $oPost->post_content = explode($aMatches[0], $oPost->post_content, 2);
1505 $sUamPostContent = $oPost->post_content[0] . " " . $sUamPostContent;
1506 }
1507
1508 $oPost->post_content = stripslashes($sUamPostContent);
1509 }
1510
1511 $oPost->post_title .= $this->adminOutput($oPost->post_type, $oPost->ID);
1512
1513 return $oPost;
1514 }
1515
1516 return null;
1517 }
1518
1519 /**
1520 * The function for the the_posts filter.
1521 *
1522 * @param array $aPosts The posts.
1523 *
1524 * @return array
1525 */
1526 public function showPost($aPosts = array())
1527 {
1528 $aShowPosts = array();
1529 $oConfig = $this->getConfig();
1530
1531 if (!is_feed() || ($oConfig->protectFeed() === true && is_feed())) {
1532 foreach ($aPosts as $iPostId) {
1533 if ($iPostId !== null) {
1534 $oPost = $this->_getPost($iPostId);
1535
1536 if ($oPost !== null) {
1537 $aShowPosts[] = $oPost;
1538 }
1539 }
1540 }
1541
1542 $aPosts = $aShowPosts;
1543 }
1544
1545 return $aPosts;
1546 }
1547
1548 /**
1549 * The function for the posts_where_paged filter.
1550 *
1551 * @param string $sSql The where sql statement.
1552 *
1553 * @return string
1554 */
1555 public function showPostSql($sSql)
1556 {
1557 $oUamAccessHandler = $this->getAccessHandler();
1558 $oConfig = $this->getConfig();
1559
1560 if ($oConfig->hidePost() === true) {
1561 $oDatabase = $this->getDatabase();
1562 $aExcludedPosts = $oUamAccessHandler->getExcludedPosts();
1563
1564 if (count($aExcludedPosts) > 0) {
1565 $sExcludedPostsStr = implode(",", $aExcludedPosts);
1566 $sSql .= " AND $oDatabase->posts.ID NOT IN($sExcludedPostsStr) ";
1567 }
1568 }
1569
1570 return $sSql;
1571 }
1572
1573 /**
1574 * The function for the wp_get_nav_menu_items filter.
1575 *
1576 * @param array $aItems The menu item.
1577 *
1578 * @return array
1579 */
1580 public function showCustomMenu($aItems)
1581 {
1582 $aShowItems = array();
1583 $aTaxonomies = $this->getTaxonomies();
1584
1585 foreach ($aItems as $oItem) {
1586 if ($oItem->object == UserAccessManager::POST_OBJECT_TYPE
1587 || $oItem->object == UserAccessManager::PAGE_OBJECT_TYPE
1588 ) {
1589 $oObject = $this->getPost($oItem->object_id);
1590
1591 if ($oObject !== null) {
1592 $oPost = $this->_getPost($oObject);
1593
1594 if ($oPost !== null) {
1595 if (isset($oPost->isLocked)) {
1596 $oItem->title = $oPost->post_title;
1597 }
1598
1599 $oItem->title .= $this->adminOutput($oItem->object, $oItem->object_id);
1600 $aShowItems[] = $oItem;
1601 }
1602 }
1603 } elseif (isset($aTaxonomies[$oItem->object])) {
1604 $oObject = $this->getTerm($oItem->object_id);
1605 $oCategory = $this->_processTerm($oObject);
1606
1607 if ($oCategory !== null && !$oCategory->isEmpty) {
1608 $oItem->title .= $this->adminOutput($oItem->object, $oItem->object_id);
1609 $aShowItems[] = $oItem;
1610 }
1611 } else {
1612 $aShowItems[] = $oItem;
1613 }
1614 }
1615
1616 return $aShowItems;
1617 }
1618
1619 /**
1620 * The function for the comments_array filter.
1621 *
1622 * @param array $aComments The comments.
1623 *
1624 * @return array
1625 */
1626 public function showComment($aComments = array())
1627 {
1628 $aShowComments = array();
1629 $oConfig = $this->getConfig();
1630 $oUamAccessHandler = $this->getAccessHandler();
1631
1632 foreach ($aComments as $oComment) {
1633 $oPost = $this->getPost($oComment->comment_post_ID);
1634 $sPostType = $oPost->post_type;
1635
1636 if ($oConfig->hideObjectTypeComments($sPostType) === true
1637 || $oConfig->hideObjectType($sPostType) === true
1638 || $this->atAdminPanel()
1639 ) {
1640 if ($oUamAccessHandler->checkObjectAccess($oPost->post_type, $oPost->ID)) {
1641 $aShowComments[] = $oComment;
1642 }
1643 } else {
1644 if (!$oUamAccessHandler->checkObjectAccess($oPost->post_type, $oPost->ID)) {
1645 $oComment->comment_content = $oConfig->getObjectTypeCommentContent($sPostType);
1646 }
1647
1648 $aShowComments[] = $oComment;
1649 }
1650 }
1651
1652 $aComments = $aShowComments;
1653
1654 return $aComments;
1655 }
1656
1657 /**
1658 * The function for the get_pages filter.
1659 *
1660 * @param array $aPages The pages.
1661 *
1662 * @return array
1663 */
1664 public function showPage($aPages = array())
1665 {
1666 $aShowPages = array();
1667 $oConfig = $this->getConfig();
1668 $oUamAccessHandler = $this->getAccessHandler();
1669
1670 foreach ($aPages as $oPage) {
1671 if ($oConfig->hidePage() === true
1672 || $this->atAdminPanel()
1673 ) {
1674 if ($oUamAccessHandler->checkObjectAccess($oPage->post_type, $oPage->ID)) {
1675 $oPage->post_title .= $this->adminOutput(
1676 $oPage->post_type,
1677 $oPage->ID
1678 );
1679 $aShowPages[] = $oPage;
1680 }
1681 } else {
1682 if (!$oUamAccessHandler->checkObjectAccess($oPage->post_type, $oPage->ID)) {
1683 if ($oConfig->hidePageTitle() === true) {
1684 $oPage->post_title = $oConfig->getPageTitle();
1685 }
1686
1687 $oPage->post_content = $oConfig->getPageContent();
1688 }
1689
1690 $oPage->post_title .= $this->adminOutput($oPage->post_type, $oPage->ID);
1691 $aShowPages[] = $oPage;
1692 }
1693 }
1694
1695 $aPages = $aShowPages;
1696
1697 return $aPages;
1698 }
1699
1700 /**
1701 * Returns the term post map.
1702 *
1703 * @return array|null
1704 */
1705 protected function getTermPostMap()
1706 {
1707 if ($this->_aTermPostMap === null) {
1708 $this->_aTermPostMap = array();
1709 $oDatabase = $this->getDatabase();
1710
1711 $sSelect = "
1712 SELECT tr.object_id, tr.term_taxonomy_id, p.post_type
1713 FROM {$oDatabase->prefix}term_relationships AS tr LEFT JOIN {$oDatabase->prefix}posts as p
1714 ON (tr.object_id = p.ID)";
1715
1716 $aResults = $oDatabase->get_results($sSelect);
1717
1718 foreach ($aResults as $oResult) {
1719 if (isset($this->_aTermPostMap[$oResult->term_taxonomy_id])) {
1720 $this->_aTermPostMap[$oResult->term_taxonomy_id] = array();
1721 }
1722
1723 $this->_aTermPostMap[$oResult->term_taxonomy_id][$oResult->object_id] = $oResult->post_type;
1724 }
1725 }
1726
1727 return $this->_aTermPostMap;
1728 }
1729
1730 /**
1731 * Modifies the content of the term by the given settings.
1732 *
1733 * @param object $oTerm The current term.
1734 *
1735 * @return object|null
1736 */
1737 protected function _processTerm($oTerm)
1738 {
1739 if (is_object($oTerm) === false || $this->atAdminPanel() === true) {
1740 return $oTerm;
1741 }
1742
1743 $oTerm->name .= $this->adminOutput(self::TERM_OBJECT_TYPE, $oTerm->term_id);
1744 $oConfig = $this->getConfig();
1745 $oUamAccessHandler = $this->getAccessHandler();
1746
1747 $oTerm->isEmpty = false;
1748
1749 if ($oUamAccessHandler->checkObjectAccess(self::TERM_OBJECT_TYPE, $oTerm->term_id)) {
1750 if ($oConfig->hidePost() === true || $oConfig->hidePage() === true) {
1751 $iTermRequest = $oTerm->term_id;
1752
1753 if ($oTerm->taxonomy == 'post_tag') {
1754 $iTermRequest = $oTerm->slug;
1755 }
1756
1757 $aTermPostMap = $this->getTermPostMap();
1758
1759 if (isset($aTermPostMap[$iTermRequest])) {
1760 $oTerm->count = count($aTermPostMap[$iTermRequest]);
1761
1762 foreach ($aTermPostMap[$iTermRequest] as $iPostId => $sPostType) {
1763 if ($oConfig->hideObjectType($sPostType) === true
1764 && !$oUamAccessHandler->checkObjectAccess($sPostType, $iPostId)
1765 ) {
1766 $oTerm->count--;
1767 }
1768 }
1769 }
1770
1771 //For post_tags
1772 if ($oTerm->taxonomy == 'post_tag' && $oTerm->count <= 0) {
1773 return null;
1774 }
1775
1776 //For categories
1777 if ($oTerm->count <= 0
1778 && $oConfig->hideEmptyCategories() === true
1779 && ($oTerm->taxonomy == 'term' || $oTerm->taxonomy == 'category')
1780 ) {
1781 $oTerm->isEmpty = true;
1782 }
1783
1784 if ($oConfig->lockRecursive() === false) {
1785 $oCurrentTerm = $oTerm;
1786
1787 while ($oCurrentTerm->parent != 0) {
1788 $oCurrentTerm = $this->getTerm($oCurrentTerm->parent);
1789
1790 if ($oUamAccessHandler->checkObjectAccess(UserAccessManager::TERM_OBJECT_TYPE, $oCurrentTerm->term_id)) {
1791 $oTerm->parent = $oCurrentTerm->term_id;
1792 break;
1793 }
1794 }
1795 }
1796 }
1797
1798 return $oTerm;
1799 }
1800
1801 return null;
1802 }
1803
1804 /**
1805 * The function for the get_ancestors filter.
1806 *
1807 * @param array $aAncestors
1808 * @param int $sObjectId
1809 * @param string $sObjectType
1810 * @param string $sResourceType
1811 *
1812 * @return array
1813 */
1814 public function showAncestors($aAncestors, $sObjectId, $sObjectType, $sResourceType)
1815 {
1816 if ($sResourceType === 'taxonomy') {
1817 $oUamAccessHandler = $this->getAccessHandler();
1818
1819 foreach ($aAncestors as $sKey => $aAncestorId) {
1820 if (!$oUamAccessHandler->checkObjectAccess(self::TERM_OBJECT_TYPE, $aAncestorId)) {
1821 unset($aAncestors[$sKey]);
1822 }
1823 }
1824 }
1825
1826 return $aAncestors;
1827 }
1828
1829 /**
1830 * The function for the get_term filter.
1831 *
1832 * @param object $oTerm
1833 *
1834 * @return null|object
1835 */
1836 public function showTerm($oTerm)
1837 {
1838 return $this->_processTerm($oTerm);
1839 }
1840
1841 /**
1842 * The function for the get_terms filter.
1843 *
1844 * @param array $aTerms The terms.
1845 * @param array $aTaxonomies The taxonomies.
1846 * @param array $aArgs The given arguments.
1847 * @param WP_Term_Query $oTermQuery The term query.
1848 *
1849 * @return array
1850 */
1851 public function showTerms($aTerms = array(), $aTaxonomies = array(), $aArgs = array(), $oTermQuery = null)
1852 {
1853 $aShowTerms = array();
1854
1855 foreach ($aTerms as $mTerm) {
1856 if (!is_object($mTerm) && is_numeric($mTerm)) {
1857 $mTerm = $this->getTerm($mTerm);
1858 }
1859
1860 $mTerm = $this->_processTerm($mTerm);
1861
1862 if ($mTerm !== null && (!isset($mTerm->isEmpty) || !$mTerm->isEmpty)) {
1863 $aShowTerms[$mTerm->term_id] = $mTerm;
1864 }
1865 }
1866
1867 foreach ($aTerms as $sKey => $mTerm) {
1868 if ($mTerm === null || is_object($mTerm) && !isset($aShowTerms[$mTerm->term_id])) {
1869 unset($aTerms[$sKey]);
1870 }
1871 }
1872
1873 return $aTerms;
1874 }
1875
1876 /**
1877 * The function for the get_previous_post_where and
1878 * the get_next_post_where filter.
1879 *
1880 * @param string $sSql The current sql string.
1881 *
1882 * @return string
1883 */
1884 public function showNextPreviousPost($sSql)
1885 {
1886 $oUamAccessHandler = $this->getAccessHandler();
1887 $oConfig = $this->getConfig();
1888
1889 if ($oConfig->hidePost() === true) {
1890 $aExcludedPosts = $oUamAccessHandler->getExcludedPosts();
1891
1892 if (count($aExcludedPosts) > 0) {
1893 $sExcludedPosts = implode(',', $aExcludedPosts);
1894 $sSql.= " AND p.ID NOT IN({$sExcludedPosts}) ";
1895 }
1896 }
1897
1898 return $sSql;
1899 }
1900
1901 /**
1902 * Returns the admin hint.
1903 *
1904 * @param string $sObjectType The object type.
1905 * @param integer $iObjectId The object id we want to check.
1906 *
1907 * @return string
1908 */
1909 public function adminOutput($sObjectType, $iObjectId)
1910 {
1911 $sOutput = "";
1912
1913 if (!$this->atAdminPanel()) {
1914 $oConfig = $this->getConfig();
1915
1916 if ($oConfig->blogAdminHint() === true) {
1917 $oCurrentUser = $this->getCurrentUser();
1918 $oUserData = $this->getUser($oCurrentUser->ID);
1919
1920 if (!isset($oUserData->user_level)) {
1921 return $sOutput;
1922 }
1923
1924 $oUamAccessHandler = $this->getAccessHandler();
1925
1926 if ($oUamAccessHandler->userIsAdmin($oCurrentUser->ID)
1927 && count($oUamAccessHandler->getUserGroupsForObject($sObjectType, $iObjectId)) > 0
1928 ) {
1929 $sOutput .= $oConfig->getBlogAdminHintText();
1930 }
1931 }
1932 }
1933
1934 return $sOutput;
1935 }
1936
1937 /**
1938 * The function for the edit_post_link filter.
1939 *
1940 * @param string $sLink The edit link.
1941 * @param integer $iPostId The _iId of the post.
1942 *
1943 * @return string
1944 */
1945 public function showGroupMembership($sLink, $iPostId)
1946 {
1947 $oUamAccessHandler = $this->getAccessHandler();
1948 $aGroups = $oUamAccessHandler->getUserGroupsForObject(self::POST_OBJECT_TYPE, $iPostId);
1949
1950 if (count($aGroups) > 0) {
1951 $sLink .= ' | '.TXT_UAM_ASSIGNED_GROUPS.': ';
1952
1953 foreach ($aGroups as $oGroup) {
1954 $sLink .= htmlentities($oGroup->getGroupName()).', ';
1955 }
1956
1957 $sLink = rtrim($sLink, ', ');
1958 }
1959
1960 return $sLink;
1961 }
1962
1963 /**
1964 * Returns the login bar.
1965 *
1966 * @return string
1967 */
1968 public function getLoginBarHtml()
1969 {
1970 if (!is_user_logged_in()) {
1971 return $this->getIncludeContents(UAM_REALPATH.'tpl/loginBar.php');
1972 }
1973
1974 return '';
1975 }
1976
1977
1978 /*
1979 * Functions for the redirection and files.
1980 */
1981
1982 /**
1983 * Returns true if permalinks are active otherwise false.
1984 *
1985 * @return boolean
1986 */
1987 public function isPermalinksActive()
1988 {
1989 $sPermalinkStructure = $this->getConfig()->getWpOption('permalink_structure');
1990 return !empty($sPermalinkStructure);
1991 }
1992
1993 /**
1994 * Redirects to a page or to content.
1995 *
1996 * @param string $sHeaders The headers which are given from wordpress.
1997 * @param object $oPageParams The params of the current page.
1998 *
1999 * @return string
2000 */
2001 public function redirect($sHeaders, $oPageParams)
2002 {
2003 $oConfig = $this->getConfig();
2004
2005 if (isset($_GET['uamgetfile']) && isset($_GET['uamfiletype'])) {
2006 $sFileUrl = $_GET['uamgetfile'];
2007 $sFileType = $_GET['uamfiletype'];
2008 $this->getFile($sFileType, $sFileUrl);
2009 } elseif (!$this->atAdminPanel() && $oConfig->getRedirect() !== 'false') {
2010 $oObject = null;
2011
2012 if (isset($oPageParams->query_vars['p'])) {
2013 $oObject = $this->getPost($oPageParams->query_vars['p']);
2014 $oObjectType = $oObject->post_type;
2015 $iObjectId = $oObject->ID;
2016 } elseif (isset($oPageParams->query_vars['page_id'])) {
2017 $oObject = $this->getPost($oPageParams->query_vars['page_id']);
2018 $oObjectType = $oObject->post_type;
2019 $iObjectId = $oObject->ID;
2020 } elseif (isset($oPageParams->query_vars['cat_id'])) {
2021 $oObject = $this->getTerm($oPageParams->query_vars['cat_id']);
2022 $oObjectType = self::TERM_OBJECT_TYPE;
2023 $iObjectId = $oObject->term_id;
2024 } elseif (isset($oPageParams->query_vars['name'])) {
2025 $oDatabase = $this->getDatabase();
2026
2027 $sPostType = UserAccessManager::POST_OBJECT_TYPE;
2028 $sPageType = UserAccessManager::PAGE_OBJECT_TYPE;
2029
2030 $sQuery = $oDatabase->prepare(
2031 "SELECT ID
2032 FROM {$oDatabase->posts}
2033 WHERE post_name = %s
2034 AND post_type IN ('{$sPostType}', '{$sPageType}')",
2035 $oPageParams->query_vars['name']
2036 );
2037
2038 $sObjectId = $oDatabase->get_var($sQuery);
2039
2040 if ($sObjectId) {
2041 $oObject = get_post($sObjectId);
2042 }
2043
2044 if ($oObject !== null) {
2045 $oObjectType = $oObject->post_type;
2046 $iObjectId = $oObject->ID;
2047 }
2048 } elseif (isset($oPageParams->query_vars['pagename'])) {
2049 $oObject = get_page_by_path($oPageParams->query_vars['pagename']);
2050
2051 if ($oObject !== null) {
2052 $oObjectType = $oObject->post_type;
2053 $iObjectId = $oObject->ID;
2054 }
2055 }
2056
2057 if ($oObject === null || $oObject !== null && isset($oObjectType) && isset($iObjectId)
2058 && !$this->getAccessHandler()->checkObjectAccess($oObjectType, $iObjectId)
2059 ) {
2060 $this->redirectUser($oObject);
2061 }
2062 }
2063
2064 return $sHeaders;
2065 }
2066
2067 /**
2068 * Returns the current url.
2069 *
2070 * @return string
2071 */
2072 public function getCurrentUrl()
2073 {
2074 if (!isset($_SERVER['REQUEST_URI'])) {
2075 $sServerRequestUri = $_SERVER['PHP_SELF'];
2076 } else {
2077 $sServerRequestUri = $_SERVER['REQUEST_URI'];
2078 }
2079
2080 $sSecure = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
2081 $aProtocols = explode("/", strtolower($_SERVER["SERVER_PROTOCOL"]));
2082 $sProtocol = $aProtocols[0].$sSecure;
2083 $sPort = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
2084
2085 return $sProtocol."://".$_SERVER['SERVER_NAME'].$sPort.$sServerRequestUri;
2086 }
2087
2088 /**
2089 * Redirects the user to his destination.
2090 *
2091 * @param object $oObject The current object we want to access.
2092 */
2093 public function redirectUser($oObject = null)
2094 {
2095 global $wp_query;
2096
2097 $blPostToShow = false;
2098 $aPosts = $wp_query->get_posts();
2099
2100 if ($oObject === null && isset($aPosts)) {
2101 foreach ($aPosts as $oPost) {
2102 if ($this->getAccessHandler()->checkObjectAccess($oPost->post_type, $oPost->ID)) {
2103 $blPostToShow = true;
2104 break;
2105 }
2106 }
2107 }
2108
2109 if (!$blPostToShow) {
2110 $oConfig = $this->getConfig();
2111 $sPermalink = null;
2112
2113 if ($oConfig->getRedirect() === 'custom_page') {
2114 $sRedirectCustomPage = $oConfig->getRedirectCustomPage();
2115 $oPost = $this->getPost($sRedirectCustomPage);
2116 $sUrl = $oPost->guid;
2117 $sPermalink = get_page_link($oPost);
2118 } elseif ($oConfig->getRedirect() === 'custom_url') {
2119 $sUrl = $oConfig->getRedirectCustomUrl();
2120 } else {
2121 $sUrl = home_url('/');
2122 }
2123
2124 if ($sUrl != $this->getCurrentUrl() && $sPermalink != $this->getCurrentUrl()) {
2125 wp_redirect($sUrl);
2126 exit;
2127 }
2128 }
2129 }
2130
2131 /**
2132 * Delivers the content of the requested file.
2133 *
2134 * @param string $sObjectType The type of the requested file.
2135 * @param string $sObjectUrl The file url.
2136 *
2137 * @return null
2138 */
2139 public function getFile($sObjectType, $sObjectUrl)
2140 {
2141 $oObject = $this->_getFileSettingsByType($sObjectType, $sObjectUrl);
2142
2143 if ($oObject === null) {
2144 return null;
2145 }
2146
2147 $sFile = null;
2148
2149 if ($this->getAccessHandler()->checkObjectAccess($oObject->type, $oObject->id)) {
2150 $sFile = $oObject->file;
2151 } elseif ($oObject->isImage) {
2152 $sFile = UAM_REALPATH.'gfx/noAccessPic.png';
2153 } else {
2154 wp_die(TXT_UAM_NO_RIGHTS);
2155 }
2156
2157 //Deliver content
2158 if (file_exists($sFile)) {
2159 $sFileName = basename($sFile);
2160
2161 /*
2162 * This only for compatibility
2163 * mime_content_type has been deprecated as the PECL extension file info
2164 * provides the same functionality (and more) in a much cleaner way.
2165 */
2166 $sFileExt = strtolower(array_pop(explode('.', $sFileName)));
2167 $aMimeTypes = $this->_getMimeTypes();
2168
2169 if (function_exists('finfo_open')) {
2170 $sFileInfo = finfo_open(FILEINFO_MIME);
2171 $sFileMimeType = finfo_file($sFileInfo, $sFile);
2172 finfo_close($sFileInfo);
2173 } elseif (function_exists('mime_content_type')) {
2174 $sFileMimeType = mime_content_type($sFile);
2175 } elseif (isset($aMimeTypes[$sFileExt])) {
2176 $sFileMimeType = $aMimeTypes[$sFileExt];
2177 } else {
2178 $sFileMimeType = 'application/octet-stream';
2179 }
2180
2181 header('Content-Description: File Transfer');
2182 header('Content-Type: '.$sFileMimeType);
2183
2184 if (!$oObject->isImage) {
2185 $sBaseName = str_replace(' ', '_', basename($sFile));
2186 header('Content-Disposition: attachment; filename="'.$sBaseName.'"');
2187 }
2188
2189 header('Content-Transfer-Encoding: binary');
2190 header('Content-Length: '.filesize($sFile));
2191
2192 $oConfig = $this->getConfig();
2193
2194 if ($oConfig->getDownloadType() === 'fopen'
2195 && !$oObject->isImage
2196 ) {
2197 $oHandler = fopen($sFile, 'r');
2198
2199 //TODO find better solution (prevent '\n' / '0A')
2200 ob_clean();
2201 flush();
2202
2203 while (!feof($oHandler)) {
2204 if (!ini_get('safe_mode')) {
2205 set_time_limit(30);
2206 }
2207
2208 echo fread($oHandler, 1024);
2209 }
2210
2211 exit;
2212 } else {
2213 ob_clean();
2214 flush();
2215 readfile($sFile);
2216 exit;
2217 }
2218 } else {
2219 wp_die(TXT_UAM_FILE_NOT_FOUND_ERROR);
2220 return null;
2221 }
2222 }
2223
2224 /**
2225 * Returns the file object by the given type and url.
2226 *
2227 * @param string $sObjectType The type of the requested file.
2228 * @param string $sObjectUrl The file url.
2229 *
2230 * @return object|null
2231 */
2232 protected function _getFileSettingsByType($sObjectType, $sObjectUrl)
2233 {
2234 $oObject = null;
2235
2236 if ($sObjectType == UserAccessManager::ATTACHMENT_OBJECT_TYPE) {
2237 $aUploadDir = wp_upload_dir();
2238 $sUploadDir = str_replace(ABSPATH, '/', $aUploadDir['basedir']);
2239 $sRegex = '/.*'.str_replace('/', '\/', $sUploadDir).'\//i';
2240 $sCleanObjectUrl = preg_replace($sRegex, '', $sObjectUrl);
2241 $sUploadUrl = str_replace('/files', $sUploadDir, $aUploadDir['baseurl']);
2242 $sObjectUrl = $sUploadUrl.'/'.ltrim($sCleanObjectUrl, '/');
2243 $oPost = $this->getPost($this->getPostIdByUrl($sObjectUrl));
2244
2245 if ($oPost !== null
2246 && $oPost->post_type == UserAccessManager::ATTACHMENT_OBJECT_TYPE
2247 ) {
2248 $oObject = new stdClass();
2249 $oObject->id = $oPost->ID;
2250 $oObject->isImage = wp_attachment_is_image($oPost->ID);
2251 $oObject->type = $sObjectType;
2252 $sMultiPath = str_replace('/files', $sUploadDir, $aUploadDir['baseurl']);
2253 $oObject->file = $aUploadDir['basedir'].str_replace($sMultiPath, '', $sObjectUrl );
2254 }
2255 } else {
2256 $aPlObject = $this->getAccessHandler()->getPlObject($sObjectType);
2257
2258 if (isset($aPlObject) && isset($aPlObject['getFileObject'])) {
2259 $oObject = $aPlObject['reference']->{$aPlObject['getFileObject']}($sObjectUrl);
2260 }
2261 }
2262
2263 return $oObject;
2264 }
2265
2266 /**
2267 * Returns the url for a locked file.
2268 *
2269 * @param string $sUrl The base url.
2270 * @param integer $iId The _iId of the file.
2271 *
2272 * @return string
2273 */
2274 public function getFileUrl($sUrl, $iId)
2275 {
2276 $oConfig = $this->getConfig();
2277
2278 if (!$this->isPermalinksActive() && $oConfig->lockFile() === true) {
2279 $oPost = &$this->getPost($iId);
2280 $aType = explode("/", $oPost->post_mime_type);
2281 $sType = $aType[1];
2282 $aFileTypes = explode(',', $oConfig->getLockedFileTypes());
2283
2284 if ($oConfig->getLockedFileTypes() === 'all' || in_array($sType, $aFileTypes)) {
2285 $sUrl = home_url('/').'?uamfiletype=attachment&uamgetfile='.$sUrl;
2286 }
2287 }
2288
2289 return $sUrl;
2290 }
2291
2292 /**
2293 * Returns the post by the given url.
2294 *
2295 * @param string $sUrl The url of the post(attachment).
2296 *
2297 * @return object The post.
2298 */
2299 public function getPostIdByUrl($sUrl)
2300 {
2301 if (isset($this->_aPostUrls[$sUrl])) {
2302 return $this->_aPostUrls[$sUrl];
2303 }
2304
2305 $this->_aPostUrls[$sUrl] = null;
2306
2307 //Filter edit string
2308 $sNewUrl = preg_split("/-e[0-9]{1,}/", $sUrl);
2309
2310 if (count($sNewUrl) == 2) {
2311 $sNewUrl = $sNewUrl[0].$sNewUrl[1];
2312 } else {
2313 $sNewUrl = $sNewUrl[0];
2314 }
2315
2316 //Filter size
2317 $sNewUrl = preg_split("/-[0-9]{1,}x[0-9]{1,}/", $sNewUrl);
2318
2319 if (count($sNewUrl) == 2) {
2320 $sNewUrl = $sNewUrl[0].$sNewUrl[1];
2321 } else {
2322 $sNewUrl = $sNewUrl[0];
2323 }
2324
2325 $oDatabase = $this->getDatabase();
2326
2327 $sSql = $oDatabase->prepare(
2328 "SELECT ID
2329 FROM ".$oDatabase->prefix."posts
2330 WHERE guid = '%s'
2331 LIMIT 1",
2332 $sNewUrl
2333 );
2334
2335 $oDbPost = $oDatabase->get_row($sSql);
2336
2337 if ($oDbPost) {
2338 $this->_aPostUrls[$sUrl] = $oDbPost->ID;
2339 }
2340
2341 return $this->_aPostUrls[$sUrl];
2342 }
2343
2344 /**
2345 * Caches the urls for the post for a later lookup.
2346 *
2347 * @param string $sUrl The url of the post.
2348 * @param object $oPost The post object.
2349 *
2350 * @return string
2351 */
2352 public function cachePostLinks($sUrl, $oPost)
2353 {
2354 $this->_aPostUrls[$sUrl] = $oPost->ID;
2355 return $sUrl;
2356 }
2357
2358 /**
2359 * Filter for Yoast SEO Plugin
2360 *
2361 * Hides the url from the site map if the user has no access
2362 *
2363 * @param string $sUrl The url to check
2364 * @param string $sType The object type
2365 * @param object $oObject The object
2366 *
2367 * @return false|string
2368 */
2369 function wpSeoUrl($sUrl, $sType, $oObject)
2370 {
2371 return ($this->getAccessHandler()->checkObjectAccess($sType, $oObject->ID)) ? $sUrl : false;
2372 }
2373 }