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

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

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