-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathBlog.m
1020 lines (870 loc) · 32.5 KB
/
Blog.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "Blog.h"
#import "WPAccount.h"
#import "AccountService.h"
@import WordPressData;
#import "WPUserAgent.h"
#import "WordPress-Swift.h"
@import SFHFKeychainUtils;
@import NSObject_SafeExpectations;
@import NSURL_IDN;
@class Comment;
static NSInteger const ImageSizeSmallWidth = 240;
static NSInteger const ImageSizeSmallHeight = 180;
static NSInteger const ImageSizeMediumWidth = 480;
static NSInteger const ImageSizeMediumHeight = 360;
static NSInteger const ImageSizeLargeWidth = 640;
static NSInteger const ImageSizeLargeHeight = 480;
static NSInteger const JetpackProfessionalYearlyPlanId = 2004;
static NSInteger const JetpackProfessionalMonthlyPlanId = 2001;
NSString * const BlogEntityName = @"Blog";
NSString * const PostFormatStandard = @"standard";
NSString * const ActiveModulesKeyStats = @"stats";
NSString * const ActiveModulesKeyPublicize = @"publicize";
NSString * const ActiveModulesKeySharingButtons = @"sharedaddy";
NSString * const OptionsKeyActiveModules = @"active_modules";
NSString * const OptionsKeyPublicizeDisabled = @"publicize_permanently_disabled";
NSString * const OptionsKeyIsAutomatedTransfer = @"is_automated_transfer";
NSString * const OptionsKeyIsAtomic = @"is_wpcom_atomic";
NSString * const OptionsKeyIsWPForTeams = @"is_wpforteams_site";
@interface Blog ()
@property (nonatomic, strong, readwrite) WordPressOrgXMLRPCApi *xmlrpcApi;
@property (nonatomic, strong, readwrite) WordPressOrgRestApi *selfHostedSiteRestApi;
@end
@implementation Blog
@dynamic accountForDefaultBlog;
@dynamic blogID;
@dynamic url;
@dynamic xmlrpc;
@dynamic apiKey;
@dynamic organizationID;
@dynamic hasOlderPosts;
@dynamic hasOlderPages;
@dynamic hasDomainCredit;
@dynamic posts;
@dynamic categories;
@dynamic tags;
@dynamic comments;
@dynamic connections;
@dynamic domains;
@dynamic inviteLinks;
@dynamic themes;
@dynamic media;
@dynamic userSuggestions;
@dynamic siteSuggestions;
@dynamic menus;
@dynamic menuLocations;
@dynamic roles;
@dynamic currentThemeId;
@dynamic lastPostsSync;
@dynamic lastPagesSync;
@dynamic lastCommentsSync;
@dynamic lastUpdateWarning;
@dynamic options;
@dynamic postTypes;
@dynamic postFormats;
@dynamic isActivated;
@dynamic account;
@dynamic isAdmin;
@dynamic isMultiAuthor;
@dynamic isHostedAtWPcom;
@dynamic icon;
@dynamic username;
@dynamic settings;
@dynamic planID;
@dynamic planTitle;
@dynamic planActiveFeatures;
@dynamic hasPaidPlan;
@dynamic sharingButtons;
@dynamic capabilities;
@dynamic userID;
@dynamic quotaSpaceAllowed;
@dynamic quotaSpaceUsed;
@dynamic pageTemplateCategories;
@dynamic publicizeInfo;
@synthesize videoPressEnabled;
@synthesize xmlrpcApi = _xmlrpcApi;
@synthesize selfHostedSiteRestApi = _selfHostedSiteRestApi;
#pragma mark - NSManagedObject subclass methods
- (void)willSave {
[super willSave];
// The `dotComID` getter has a speicial code to _update_ `blogID` value.
// This is a weird patch to make sure `blogID` is set to a correct value.
//
// It's important that calling `[self dotComID]` repeatedly only updates
// `Blog` instance once, which is the case at the moment.
[self dotComID];
}
- (void)prepareForDeletion
{
[super prepareForDeletion];
// delete stored password in the keychain for self-hosted sites.
if ([self.username length] > 0 && [self.xmlrpc length] > 0) {
self.password = nil;
}
if (self.account == nil) {
[self deleteApplicationToken];
}
[_xmlrpcApi invalidateAndCancelTasks];
[_selfHostedSiteRestApi invalidateAndCancelTasks];
// Remove the self-hosted site cookies from the shared cookie storage.
if (self.account == nil && self.url != nil) {
NSURL *siteURL = [NSURL URLWithString:self.url];
if (siteURL != nil) {
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookiesForURL:siteURL]) {
[cookieJar deleteCookie:cookie];
}
}
}
}
- (void)didTurnIntoFault
{
[super didTurnIntoFault];
// Clean up instance variables
self.xmlrpcApi = nil;
self.selfHostedSiteRestApi = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -
#pragma mark Custom methods
- (NSNumber *)organizationID {
NSNumber *organizationID = [self primitiveValueForKey:@"organizationID"];
if (organizationID == nil) {
return @0;
} else {
return organizationID;
}
}
- (BOOL)isAtomic
{
NSNumber *value = (NSNumber *)[self getOptionValue:OptionsKeyIsAtomic];
return [value boolValue];
}
- (BOOL)isWPForTeams
{
NSNumber *value = (NSNumber *)[self getOptionValue:OptionsKeyIsWPForTeams];
return [value boolValue];
}
- (BOOL)isAutomatedTransfer
{
NSNumber *value = (NSNumber *)[self getOptionValue:OptionsKeyIsAutomatedTransfer];
return [value boolValue];
}
// Used as a key to store passwords, if you change the algorithm, logins will break
- (NSString *)displayURL
{
if (self.url == nil) {
DDLogInfo(@"Blog display URL is nil");
return nil;
}
NSError *error = nil;
NSRegularExpression *protocol = [NSRegularExpression regularExpressionWithPattern:@"http(s?)://" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [NSString stringWithFormat:@"%@", [protocol stringByReplacingMatchesInString:self.url options:0 range:NSMakeRange(0, [self.url length]) withTemplate:@""]];
if ([result hasSuffix:@"/"]) {
result = [result substringToIndex:[result length] - 1];
}
NSString *decodedResult = [NSURL IDNDecodedHostname:result];
NSAssert(decodedResult != nil, @"Decoded url shouldn't be nil");
if (decodedResult == nil) {
DDLogInfo(@"displayURL: decoded url is nil: %@", self.url);
return result;
}
return decodedResult;
}
- (NSString *)hostURL
{
return [self displayURL];
}
- (NSString *)homeURL
{
NSString *homeURL = [self getOptionValue:@"home_url"];
if (!homeURL) {
homeURL = self.url;
}
return homeURL;
}
- (NSString *)hostname
{
NSString *hostname = [[NSURL URLWithString:self.xmlrpc] host];
if (hostname == nil) {
NSError *error = nil;
NSRegularExpression *protocol = [NSRegularExpression regularExpressionWithPattern:@"^.*://" options:NSRegularExpressionCaseInsensitive error:&error];
hostname = [protocol stringByReplacingMatchesInString:self.url options:0 range:NSMakeRange(0, [self.url length]) withTemplate:@""];
}
// NSURL seems to not recongnize some TLDs like .me and .it, which results in hostname returning a full path.
// This can break reachibility (among other things) for the blog.
// As a saftey net, make sure we drop any path component before returning the hostname.
NSArray *parts = [hostname componentsSeparatedByString:@"/"];
if (parts.count) {
hostname = [parts firstObject];
}
return hostname;
}
- (NSString *)loginUrl
{
NSString *loginUrl = [self getOptionValue:@"login_url"];
if (!loginUrl) {
loginUrl = [self urlWithPath:@"wp-login.php"];
}
return loginUrl;
}
- (NSString *)urlWithPath:(NSString *)path
{
if (!path || !self.xmlrpc) {
DDLogError(@"Blog: Error creating urlWithPath.");
return nil;
}
NSError *error = nil;
NSRegularExpression *xmlrpc = [NSRegularExpression regularExpressionWithPattern:@"xmlrpc.php$" options:NSRegularExpressionCaseInsensitive error:&error];
return [xmlrpc stringByReplacingMatchesInString:self.xmlrpc options:0 range:NSMakeRange(0, [self.xmlrpc length]) withTemplate:path];
}
- (NSString *)adminUrlWithPath:(NSString *)path
{
NSString *adminBaseUrl = [self getOptionValue:@"admin_url"];
if (!adminBaseUrl) {
adminBaseUrl = [self urlWithPath:@"wp-admin/"];
}
if (![adminBaseUrl hasSuffix:@"/"]) {
adminBaseUrl = [adminBaseUrl stringByAppendingString:@"/"];
}
return [NSString stringWithFormat:@"%@%@", adminBaseUrl, path];
}
- (NSArray *)sortedCategories
{
NSSortDescriptor *sortNameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"categoryName"
ascending:YES
selector:@selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortNameDescriptor, nil];
return [[self.categories allObjects] sortedArrayUsingDescriptors:sortDescriptors];
}
- (NSArray *)sortedPostFormats
{
if ([self.postFormats count] == 0) {
return @[];
}
NSMutableArray *sortedFormats = [NSMutableArray arrayWithCapacity:[self.postFormats count]];
if (self.postFormats[PostFormatStandard]) {
[sortedFormats addObject:PostFormatStandard];
}
NSArray *sortedNonStandardFormats = [[self.postFormats keysSortedByValueUsingSelector:@selector(localizedCaseInsensitiveCompare:)] wp_filter:^BOOL(id obj) {
return ![obj isEqual:PostFormatStandard];
}];
[sortedFormats addObjectsFromArray:sortedNonStandardFormats];
return [NSArray arrayWithArray:sortedFormats];
}
- (NSArray *)sortedPostFormatNames
{
return [[self sortedPostFormats] wp_map:^id(NSString *key) {
return self.postFormats[key];
}];
}
- (NSArray *)sortedConnections
{
NSSortDescriptor *sortServiceDescriptor = [[NSSortDescriptor alloc] initWithKey:@"service"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];
NSSortDescriptor *sortExternalNameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"externalName"
ascending:YES
selector:@selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = @[sortServiceDescriptor, sortExternalNameDescriptor];
return [[self.connections allObjects] sortedArrayUsingDescriptors:sortDescriptors];
}
- (NSArray<Role *> *)sortedRoles
{
return [self.roles sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]]];
}
- (NSString *)defaultPostFormatText
{
return [self postFormatTextFromSlug:self.settings.defaultPostFormat];
}
- (BOOL)hasMappedDomain {
if (![self isHostedAtWPcom]) {
return NO;
}
NSURL *unmappedURL = [NSURL URLWithString:[self getOptionValue:@"unmapped_url"]];
NSURL *homeURL = [NSURL URLWithString:[self homeURL]];
return ![[unmappedURL host] isEqualToString:[homeURL host]];
}
- (BOOL)hasIcon
{
// A blog without an icon has the blog url in icon, so we can't directly check its
// length to determine if we have an icon or not
return self.icon.length > 0 ? [NSURL URLWithString:self.icon].pathComponents.count > 1 : NO;
}
- (nullable NSTimeZone *)timeZone
{
CGFloat const OneHourInSeconds = 60.0 * 60.0;
NSString *timeZoneName = [self getOptionValue:@"timezone"];
NSNumber *gmtOffSet = [self getOptionValue:@"gmt_offset"];
id optionValue = [self getOptionValue:@"time_zone"];
NSTimeZone *timeZone = nil;
if (timeZoneName.length > 0) {
timeZone = [NSTimeZone timeZoneWithName:timeZoneName];
}
if (!timeZone && gmtOffSet != nil) {
timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtOffSet.floatValue * OneHourInSeconds)];
}
if (!timeZone && optionValue != nil) {
NSInteger timeZoneOffsetSeconds = [optionValue floatValue] * OneHourInSeconds;
timeZone = [NSTimeZone timeZoneForSecondsFromGMT:timeZoneOffsetSeconds];
}
if (!timeZone) {
timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
}
return timeZone;
}
- (NSString *)postFormatTextFromSlug:(NSString *)postFormatSlug
{
NSDictionary *allFormats = self.postFormats;
NSString *formatText = postFormatSlug;
if (postFormatSlug && allFormats[postFormatSlug]) {
formatText = allFormats[postFormatSlug];
}
// Default to standard if no name is found
if ((formatText == nil || [formatText isEqualToString:@""]) && allFormats[PostFormatStandard]) {
formatText = allFormats[PostFormatStandard];
}
return formatText;
}
/// Call this method to know whether the blog is private.
///
- (BOOL)isPrivate
{
return [self.settings.privacy isEqualToNumber:@(SiteVisibilityPrivate)];
}
/// Call this method to know whether the blog is private AND hosted at WP.com.
///
- (BOOL)isPrivateAtWPCom
{
return (self.isHostedAtWPcom && [self isPrivate]);
}
- (SiteVisibility)siteVisibility
{
switch ([self.settings.privacy integerValue]) {
case (SiteVisibilityHidden):
return SiteVisibilityHidden;
break;
case (SiteVisibilityPublic):
return SiteVisibilityPublic;
break;
case (SiteVisibilityPrivate):
return SiteVisibilityPrivate;
break;
default:
break;
}
return SiteVisibilityUnknown;
}
- (void)setSiteVisibility:(SiteVisibility)siteVisibility
{
switch (siteVisibility) {
case (SiteVisibilityHidden):
self.settings.privacy = @(SiteVisibilityHidden);
break;
case (SiteVisibilityPublic):
self.settings.privacy = @(SiteVisibilityPublic);
break;
case (SiteVisibilityPrivate):
self.settings.privacy = @(SiteVisibilityPrivate);
break;
default:
NSParameterAssert(siteVisibility >= SiteVisibilityPrivate && siteVisibility <= SiteVisibilityPublic);
break;
}
}
- (NSDictionary *)getImageResizeDimensions
{
CGSize smallSize, mediumSize, largeSize;
CGFloat smallSizeWidth = [[self getOptionValue:@"thumbnail_size_w"] floatValue] > 0 ? [[self getOptionValue:@"thumbnail_size_w"] floatValue] : ImageSizeSmallWidth;
CGFloat smallSizeHeight = [[self getOptionValue:@"thumbnail_size_h"] floatValue] > 0 ? [[self getOptionValue:@"thumbnail_size_h"] floatValue] : ImageSizeSmallHeight;
CGFloat mediumSizeWidth = [[self getOptionValue:@"medium_size_w"] floatValue] > 0 ? [[self getOptionValue:@"medium_size_w"] floatValue] : ImageSizeMediumWidth;
CGFloat mediumSizeHeight = [[self getOptionValue:@"medium_size_h"] floatValue] > 0 ? [[self getOptionValue:@"medium_size_h"] floatValue] : ImageSizeMediumHeight;
CGFloat largeSizeWidth = [[self getOptionValue:@"large_size_w"] floatValue] > 0 ? [[self getOptionValue:@"large_size_w"] floatValue] : ImageSizeLargeWidth;
CGFloat largeSizeHeight = [[self getOptionValue:@"large_size_h"] floatValue] > 0 ? [[self getOptionValue:@"large_size_h"] floatValue] : ImageSizeLargeHeight;
smallSize = CGSizeMake(smallSizeWidth, smallSizeHeight);
mediumSize = CGSizeMake(mediumSizeWidth, mediumSizeHeight);
largeSize = CGSizeMake(largeSizeWidth, largeSizeHeight);
return @{@"smallSize": [NSValue valueWithCGSize:smallSize],
@"mediumSize": [NSValue valueWithCGSize:mediumSize],
@"largeSize": [NSValue valueWithCGSize:largeSize]};
}
- (void)setXmlrpc:(NSString *)xmlrpc
{
[self willChangeValueForKey:@"xmlrpc"];
[self setPrimitiveValue:xmlrpc forKey:@"xmlrpc"];
[self didChangeValueForKey:@"xmlrpc"];
// Reset the api client so next time we use the new XML-RPC URL
self.xmlrpcApi = nil;
}
- (NSString *)version
{
// Ensure the value being returned is a string to prevent a crash when using this value in Swift
id value = [self getOptionValue:@"software_version"];
// If its a string, then return its value 🎉
if([value isKindOfClass:NSString.class]) {
return value;
}
// If its not a string, but can become a string, then convert it
if([value respondsToSelector:@selector(stringValue)]) {
return [value stringValue];
}
// If the value is an unknown type, and can not become a string, then default to a blank string.
return @"";
}
- (NSString *)password
{
return [SFHFKeychainUtils getPasswordForUsername:self.username andServiceName:self.xmlrpc accessGroup:nil error:nil];
}
- (void)setPassword:(NSString *)password
{
NSAssert(self.username != nil, @"Can't set password if we don't know the username yet");
NSAssert(self.xmlrpc != nil, @"Can't set password if we don't know the XML-RPC endpoint yet");
if (password) {
[SFHFKeychainUtils storeUsername:self.username
andPassword:password
forServiceName:self.xmlrpc
accessGroup:nil
updateExisting:YES
error:nil];
} else {
[SFHFKeychainUtils deleteItemForUsername:self.username
andServiceName:self.xmlrpc
accessGroup:nil
error:nil];
}
}
- (NSString *)authToken
{
return self.account.authToken;
}
- (NSString *)usernameForSite
{
if (self.username) {
return self.username;
} else if (self.account && self.isAccessibleThroughWPCom) {
return self.account.username;
} else {
// FIXME: Figure out how to get the self hosted username when using Jetpack REST (@koke 2015-06-15)
return nil;
}
}
- (BOOL)canBlaze
{
return [[self getOptionValue:@"can_blaze"] boolValue] && self.isAdmin;
}
- (BOOL)supportsFeaturedImages
{
id hasSupport = [self getOptionValue:@"post_thumbnail"];
if (hasSupport) {
return [hasSupport boolValue];
}
return NO;
}
- (BOOL)supports:(BlogFeature)feature
{
switch (feature) {
case BlogFeatureRemovable:
return ![self accountIsDefaultAccount];
case BlogFeatureVisibility:
/*
See -[BlogListViewController fetchRequestPredicateForHideableBlogs]
If the logic for this changes that needs to be updated as well
*/
return [self accountIsDefaultAccount];
case BlogFeaturePeople:
return [self supportsRestApi] && self.isListingUsersAllowed;
case BlogFeatureWPComRESTAPI:
case BlogFeatureCommentLikes:
return [self supportsRestApi];
case BlogFeatureStats:
return [self supportsRestApi] && [self isViewingStatsAllowed];
case BlogFeatureStockPhotos:
return [self supportsRestApi] && [JetpackFeaturesRemovalCoordinator jetpackFeaturesEnabled];
case BlogFeatureTenor:
return [JetpackFeaturesRemovalCoordinator jetpackFeaturesEnabled];
case BlogFeatureSharing:
return [self supportsSharing];
case BlogFeatureOAuth2Login:
return [self isHostedAtWPcom];
case BlogFeatureMentions:
return [self isAccessibleThroughWPCom];
case BlogFeatureXposts:
return [self isAccessibleThroughWPCom];
case BlogFeatureReblog:
case BlogFeaturePlans:
return [self isHostedAtWPcom] && [self isAdmin];
case BlogFeaturePluginManagement:
return [self supportsPluginManagement] && [self isAdmin];
case BlogFeatureJetpackImageSettings:
return [self supportsJetpackImageSettings];
case BlogFeatureJetpackSettings:
return [self supportsJetpackSettings];
case BlogFeaturePushNotifications:
return [self supportsPushNotifications];
case BlogFeatureThemeBrowsing:
return [self supportsRestApi] && [self isAdmin];
case BlogFeatureActivity: {
// For now Activity is suported for admin users
return [self supportsRestApi] && [self isAdmin];
}
case BlogFeatureCustomThemes:
return [self supportsRestApi] && [self isAdmin] && ![self isHostedAtWPcom];
case BlogFeaturePremiumThemes:
return [self supports:BlogFeatureCustomThemes] && (self.planID.integerValue == JetpackProfessionalYearlyPlanId
|| self.planID.integerValue == JetpackProfessionalMonthlyPlanId);
case BlogFeatureMenus:
return [self supportsRestApi] && [self isAdmin];
case BlogFeaturePrivate:
// Private visibility is only supported by wpcom blogs
return [self isHostedAtWPcom];
case BlogFeatureSiteManagement:
return [self supportsSiteManagementServices];
case BlogFeatureDomains:
return ([self isHostedAtWPcom] || [self isAtomic]) && [self isAdmin] && ![self isWPForTeams];
case BlogFeatureNoncePreviews:
return [self supportsRestApi] && ![self isHostedAtWPcom];
case BlogFeatureMediaMetadataEditing:
return [self isAdmin];
case BlogFeatureMediaAltEditing:
// alt is not supported via XML-RPC API
// https://core.trac.wordpress.org/ticket/58582
// https://github.com/wordpress-mobile/WordPress-Android/issues/18514#issuecomment-1589752274
return [self supportsRestApi];
case BlogFeatureMediaDeletion:
return [self isAdmin];
case BlogFeatureHomepageSettings:
return [self supportsRestApi] && [self isAdmin];
case BlogFeatureContactInfo:
return [self supportsContactInfo];
case BlogFeatureBlockEditorSettings:
return [self supportsBlockEditorSettings];
case BlogFeatureLayoutGrid:
return [self supportsLayoutGrid];
case BlogFeatureTiledGallery:
return [self supportsTiledGallery];
case BlogFeatureVideoPress:
return [self supportsVideoPress];
case BlogFeatureVideoPressV5:
return [self supportsVideoPressV5];
case BlogFeatureFacebookEmbed:
return [self supportsEmbedVariation: @"9.0"];
case BlogFeatureInstagramEmbed:
return [self supportsEmbedVariation: @"9.0"];
case BlogFeatureLoomEmbed:
return [self supportsEmbedVariation: @"9.0"];
case BlogFeatureSmartframeEmbed:
return [self supportsEmbedVariation: @"10.2"];
case BlogFeatureFileDownloadsStats:
return [self isHostedAtWPcom];
case BlogFeatureBlaze:
return [self canBlaze];
case BlogFeaturePages:
return [self isListingPagesAllowed];
case BlogFeatureSiteMonitoring:
return [self isAdmin] && [self isAtomic];
}
}
-(BOOL)supportsSharing
{
return [self supportsPublicize] || [self supportsShareButtons];
}
- (BOOL)supportsPublicize
{
// Publicize is only supported via REST
if (![self supports:BlogFeatureWPComRESTAPI]) {
return NO;
}
if (![self isPublishingPostsAllowed]) {
return NO;
}
if (self.isHostedAtWPcom) {
// For WordPress.com YES unless it's disabled
return ![[self getOptionValue:OptionsKeyPublicizeDisabled] boolValue];
} else {
// For Jetpack, check if the module is enabled
return [self jetpackPublicizeModuleEnabled];
}
}
- (BOOL)supportsShareButtons
{
// Share Button settings are only supported via REST, and for admins
if (![self isAdmin] || ![self supports:BlogFeatureWPComRESTAPI]) {
return NO;
}
if (self.isHostedAtWPcom) {
// For WordPress.com YES
return YES;
} else {
// For Jetpack, check if the module is enabled
return [self jetpackSharingButtonsModuleEnabled];
}
}
- (BOOL)isStatsActive
{
return [self jetpackStatsModuleEnabled] || [self isHostedAtWPcom];
}
- (BOOL)supportsPushNotifications
{
return [self accountIsDefaultAccount];
}
- (BOOL)supportsJetpackImageSettings
{
return [self hasRequiredJetpackVersion:@"5.6"];
}
- (BOOL)supportsPluginManagement
{
BOOL hasRequiredJetpack = [self hasRequiredJetpackVersion:@"5.6"];
BOOL isTransferrable = self.isHostedAtWPcom
&& self.hasBusinessPlan
&& self.siteVisibility != SiteVisibilityPrivate;
BOOL supports = isTransferrable || hasRequiredJetpack;
// If the site is not hosted on WP.com we can still manage plugins directly using the WP.org rest API
// Reference: https://make.wordpress.org/core/2020/07/16/new-and-modified-rest-api-endpoints-in-wordpress-5-5/
if(!supports && !self.account){
supports = !self.isHostedAtWPcom
&& self.selfHostedSiteRestApi
&& [self hasRequiredWordPressVersion:@"5.5"];
}
return supports;
}
- (BOOL)supportsContactInfo
{
return [self hasRequiredJetpackVersion:@"8.5"] || self.isHostedAtWPcom;
}
- (BOOL)supportsLayoutGrid
{
return self.isHostedAtWPcom || self.isAtomic;
}
- (BOOL)supportsTiledGallery
{
return self.isHostedAtWPcom;
}
- (BOOL)supportsVideoPress
{
return self.isHostedAtWPcom;
}
- (BOOL)supportsVideoPressV5
{
return self.isHostedAtWPcom || self.isAtomic || [self hasRequiredJetpackVersion:@"8.5"];
}
- (BOOL)supportsEmbedVariation:(NSString *)requiredJetpackVersion
{
return [self hasRequiredJetpackVersion:requiredJetpackVersion] || self.isHostedAtWPcom;
}
- (BOOL)supportsJetpackSettings
{
return [JetpackFeaturesRemovalCoordinator jetpackFeaturesEnabled]
&& [self supportsRestApi]
&& ![self isHostedAtWPcom]
&& [self isAdmin];
}
- (BOOL)accountIsDefaultAccount
{
return [[self account] isDefaultWordPressComAccount];
}
- (NSNumber *)dotComID
{
[self willAccessValueForKey:@"blogID"];
NSNumber *dotComID = [self primitiveValueForKey:@"blogID"];
if (dotComID.integerValue == 0) {
dotComID = self.jetpack.siteID;
if (dotComID.integerValue > 0) {
self.dotComID = dotComID;
}
}
[self didAccessValueForKey:@"blogID"];
return dotComID;
}
- (void)setDotComID:(NSNumber *)dotComID
{
[self willChangeValueForKey:@"blogID"];
[self setPrimitiveValue:dotComID forKey:@"blogID"];
[self didChangeValueForKey:@"blogID"];
}
- (NSSet *)allowedFileTypes
{
NSArray *allowedFileTypes = [self.options arrayForKeyPath:@"allowed_file_types.value"];
if (!allowedFileTypes || allowedFileTypes.count == 0) {
return nil;
}
return [NSSet setWithArray:allowedFileTypes];
}
- (void)setOptions:(NSDictionary *)options
{
[self willChangeValueForKey:@"options"];
[self setPrimitiveValue:options forKey:@"options"];
[self didChangeValueForKey:@"options"];
self.siteVisibility = (SiteVisibility)([[self getOptionValue:@"blog_public"] integerValue]);
// HACK:Sergio Estevao (2015-08-31): Because there is no direct way to
// know if a user has permissions to change the options we check if the blog title property is read only or not.
// (Moved from BlogService, 2016-01-28 by aerych)
if ([self.options numberForKeyPath:@"blog_title.readonly"]) {
self.isAdmin = ![[self.options numberForKeyPath:@"blog_title.readonly"] boolValue];
}
}
+ (NSSet *)keyPathsForValuesAffectingJetpack
{
return [NSSet setWithObject:@"options"];
}
- (NSString *)logDescription
{
NSString *extra = @"";
if (self.account) {
extra = [NSString stringWithFormat:@" wp.com account: %@ blogId: %@ plan: %@ (%@)", self.account ? self.account.username : @"NO", self.dotComID, self.planTitle, self.planID];
} else {
extra = [NSString stringWithFormat:@" jetpack: %@", [self.jetpack description]];
}
return [NSString stringWithFormat:@"<Blog Name: %@ URL: %@ XML-RPC: %@%@ ObjectID: %@>", self.settings.name, self.url, self.xmlrpc, extra, self.objectID.URIRepresentation];
}
- (NSString *)supportDescription
{
// Gather information
NSString *blogType = [NSString stringWithFormat:@"Type: (%@)", [self stateDescription]];
NSString *urlType = [self wordPressComRestApi] ? @"REST" : @"Self-hosted";
NSString *url = [NSString stringWithFormat:@"URL: %@", self.url];
NSString *username;
NSString *planDescription;
if (self.account) {
planDescription = [NSString stringWithFormat:@"Plan: %@ (%@)", self.planTitle, self.planID];
} else {
username = [self.jetpack connectedUsername];
}
NSString *jetpackVersion;
if ([self.jetpack isInstalled]) {
jetpackVersion = [NSString stringWithFormat:@"Jetpack-version: %@", [self.jetpack version]];
}
// Add information to array in the order we want to display it.
NSMutableArray *blogInformation = [[NSMutableArray alloc] init];
[blogInformation addObject:blogType];
if (username) {
[blogInformation addObject:username];
}
[blogInformation addObject:urlType];
[blogInformation addObject:url];
if (planDescription) {
[blogInformation addObject:planDescription];
}
if (jetpackVersion) {
[blogInformation addObject:jetpackVersion];
}
// Combine and return.
return [NSString stringWithFormat:@"<%@>", [blogInformation componentsJoinedByString:@" "]];
}
- (NSString *)stateDescription
{
if (self.account) {
return @"wpcom";
}
if ([self.jetpack isConnected]) {
NSString *apiType = [self wordPressComRestApi] ? @"REST" : @"XML-RPC";
return [NSString stringWithFormat:@"jetpack_connected - %@", apiType];
}
if ([self.jetpack isInstalled]) {
return @"self-hosted - jetpack_installed";
}
return @"self_hosted";
}
#pragma mark - api accessor
- (WordPressOrgXMLRPCApi *)xmlrpcApi
{
NSURL *xmlRPCEndpoint = [NSURL URLWithString:self.xmlrpc];
if (_xmlrpcApi == nil) {
if (xmlRPCEndpoint != nil) {
_xmlrpcApi = [[WordPressOrgXMLRPCApi alloc] initWithEndpoint:xmlRPCEndpoint
userAgent:[WPUserAgent wordPressUserAgent]];
}
}
return _xmlrpcApi;
}
- (WordPressOrgRestApi *)selfHostedSiteRestApi
{
if (_selfHostedSiteRestApi == nil) {
_selfHostedSiteRestApi = self.account == nil ? [[WordPressOrgRestApi alloc] initWithBlog:self] : nil;
}
return _selfHostedSiteRestApi;
}
- (WordPressComRestApi *)wordPressComRestApi
{
if (self.account) {
return self.account.wordPressComRestApi;
}
return nil;
}
- (BOOL)isAccessibleThroughWPCom {
return self.wordPressComRestApi != nil;
}
- (BOOL)supportsRestApi {
// We don't want to check for `restApi` as it can be `nil` when the token
// is missing from the keychain.
return self.account != nil;
}
#pragma mark - Jetpack
- (BOOL)jetpackActiveModule:(NSString *)moduleName
{
NSArray *activeModules = (NSArray *)[self getOptionValue:OptionsKeyActiveModules];
return [activeModules containsObject:moduleName] ?: NO;
}
- (BOOL)jetpackStatsModuleEnabled
{
return [self jetpackActiveModule:ActiveModulesKeyStats];
}
- (BOOL)jetpackPublicizeModuleEnabled
{
return [self jetpackActiveModule:ActiveModulesKeyPublicize];
}
- (BOOL)jetpackSharingButtonsModuleEnabled
{
return [self jetpackActiveModule:ActiveModulesKeySharingButtons];
}
- (BOOL)isBasicAuthCredentialStored
{
NSURLCredentialStorage *storage = [NSURLCredentialStorage sharedCredentialStorage];
NSURL *url = [NSURL URLWithString:self.url];
NSDictionary * credentials = storage.allCredentials;
for (NSURLProtectionSpace *protectionSpace in credentials.allKeys) {
if ( [protectionSpace.host isEqual:url.host]
&& (protectionSpace.port == ([url.port integerValue] ? : 80))
&& (protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic)) {
return YES;
}
}
return NO;
}
- (BOOL)hasRequiredJetpackVersion:(NSString *)requiredJetpackVersion
{
return [self supportsRestApi]
&& ![self isHostedAtWPcom]
&& [self.jetpack.version compare:requiredJetpackVersion options:NSNumericSearch] != NSOrderedAscending;
}
/// Checks the blogs installed WordPress version is more than or equal to the requiredVersion
/// @param requiredVersion The minimum version to check for
- (BOOL)hasRequiredWordPressVersion:(NSString *)requiredVersion
{
return [self.version compare:requiredVersion options:NSNumericSearch] != NSOrderedAscending;
}
#pragma mark - Private Methods
- (id)getOptionValue:(NSString *)name
{
__block id optionValue;
[self.managedObjectContext performBlockAndWait:^{
if ( self.options == nil || (self.options.count == 0) ) {
optionValue = nil;
}
NSDictionary *currentOption = [self.options objectForKey:name];
optionValue = currentOption[@"value"];
}];