Passed
Push — staging ( 81ba0c...d71a8f )
by Woeler
14:37 queued 10s
created

bundles/PluginBundle/Helper/IntegrationHelper.php (3 issues)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\PluginBundle\Helper;
13
14
use Doctrine\ORM\EntityManager;
15
use Mautic\CoreBundle\Factory\MauticFactory;
16
use Mautic\CoreBundle\Helper\BundleHelper;
17
use Mautic\CoreBundle\Helper\CoreParametersHelper;
18
use Mautic\CoreBundle\Helper\DateTimeHelper;
19
use Mautic\CoreBundle\Helper\PathsHelper;
20
use Mautic\CoreBundle\Helper\TemplatingHelper;
21
use Mautic\PluginBundle\Entity\Integration;
22
use Mautic\PluginBundle\Entity\Plugin;
23
use Mautic\PluginBundle\Integration\AbstractIntegration;
24
use Mautic\PluginBundle\Model\PluginModel;
25
use Symfony\Component\DependencyInjection\Container;
26
use Symfony\Component\Finder\Finder;
27
use Symfony\Component\HttpKernel\Kernel;
28
29
/**
30
 * Class IntegrationHelper.
31
 */
32
class IntegrationHelper
33
{
34
    /**
35
     * @var Container
36
     */
37
    private $container;
38
39
    /**
40
     * @var EntityManager
41
     */
42
    protected $em;
43
44
    /**
45
     * @var PathsHelper
46
     */
47
    protected $pathsHelper;
48
49
    /**
50
     * @var BundleHelper
51
     */
52
    protected $bundleHelper;
53
54
    /**
55
     * @var CoreParametersHelper
56
     */
57
    protected $coreParametersHelper;
58
59
    /**
60
     * @var TemplatingHelper
61
     */
62
    protected $templatingHelper;
63
64
    /**
65
     * @var PluginModel
66
     */
67
    protected $pluginModel;
68
69
    /**
70
     * @deprecated 2.8.2 To be removed in 3.0
71
     *
72
     * @var MauticFactory
73
     */
74
    protected $factory;
75
76
    private $integrations = [];
77
78
    private $available = [];
79
80
    private $byFeatureList = [];
81
82
    private $byPlugin = [];
83
84
    /**
85
     * IntegrationHelper constructor.
86
     *
87
     * @param Kernel               $kernel
88
     * @param EntityManager        $em
89
     * @param PathsHelper          $pathsHelper
90
     * @param BundleHelper         $bundleHelper
91
     * @param CoreParametersHelper $coreParametersHelper
92
     * @param TemplatingHelper     $templatingHelper
93
     * @param PluginModel          $pluginModel
94
     */
95
    public function __construct(Kernel $kernel, EntityManager $em, PathsHelper $pathsHelper, BundleHelper $bundleHelper, CoreParametersHelper $coreParametersHelper, TemplatingHelper $templatingHelper, PluginModel $pluginModel)
96
    {
97
        $this->container            = $kernel->getContainer();
98
        $this->em                   = $em;
99
        $this->pathsHelper          = $pathsHelper;
100
        $this->bundleHelper         = $bundleHelper;
101
        $this->pluginModel          = $pluginModel;
102
        $this->coreParametersHelper = $coreParametersHelper;
103
        $this->templatingHelper     = $templatingHelper;
104
        $this->factory              = $this->container->get('mautic.factory');
0 ignored issues
show
Deprecated Code introduced by
The property Mautic\PluginBundle\Help...grationHelper::$factory has been deprecated: 2.8.2 To be removed in 3.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

104
        /** @scrutinizer ignore-deprecated */ $this->factory              = $this->container->get('mautic.factory');

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
105
    }
106
107
    /**
108
     * Get a list of integration helper classes.
109
     *
110
     * @param array|string $specificIntegrations
111
     * @param array        $withFeatures
112
     * @param bool         $alphabetical
113
     * @param null|int     $pluginFilter
114
     * @param bool|false   $publishedOnly
115
     *
116
     * @return mixed
117
     */
118
    public function getIntegrationObjects($specificIntegrations = null, $withFeatures = null, $alphabetical = false, $pluginFilter = null, $publishedOnly = false)
119
    {
120
        // Build the service classes
121
        if (empty($this->available)) {
122
            $this->available = [];
123
124
            // Get currently installed integrations
125
            $integrationSettings = $this->getIntegrationSettings();
126
127
            // And we'll be scanning the addon bundles for additional classes, so have that data on standby
128
            $plugins = $this->bundleHelper->getPluginBundles();
129
130
            // Get a list of already installed integrations
131
            $integrationRepo = $this->em->getRepository('MauticPluginBundle:Integration');
132
            //get a list of plugins for filter
133
            $installedPlugins = $this->pluginModel->getEntities(
134
                [
135
                    'hydration_mode' => 'hydrate_array',
136
                    'index'          => 'bundle',
137
                ]
138
            );
139
140
            $newIntegrations = [];
141
142
            // Scan the plugins for integration classes
143
            foreach ($plugins as $plugin) {
144
                // Do not list the integration if the bundle has not been "installed"
145
                if (!isset($plugin['bundle']) || !isset($installedPlugins[$plugin['bundle']])) {
146
                    continue;
147
                }
148
149
                if (is_dir($plugin['directory'].'/Integration')) {
150
                    $finder = new Finder();
151
                    $finder->files()->name('*Integration.php')->in($plugin['directory'].'/Integration')->ignoreDotFiles(true);
152
153
                    $id                  = $installedPlugins[$plugin['bundle']]['id'];
154
                    $this->byPlugin[$id] = [];
155
                    $pluginReference     = $this->em->getReference('MauticPluginBundle:Plugin', $id);
156
                    $pluginNamespace     = str_replace('MauticPlugin', '', $plugin['bundle']);
157
158
                    foreach ($finder as $file) {
159
                        $integrationName = substr($file->getBaseName(), 0, -15);
160
161
                        if (!isset($integrationSettings[$integrationName])) {
162
                            $newIntegration = new Integration();
163
                            $newIntegration->setName($integrationName)
164
                                ->setPlugin($pluginReference);
165
                            $integrationSettings[$integrationName] = $newIntegration;
166
                            $integrationContainerKey               = strtolower("mautic.integration.{$integrationName}");
167
168
                            // Initiate the class in order to get the features supported
169
                            if ($this->container->has($integrationContainerKey)) {
170
                                $this->integrations[$integrationName] = $this->container->get($integrationContainerKey);
171
172
                                $features = $this->integrations[$integrationName]->getSupportedFeatures();
173
                                $newIntegration->setSupportedFeatures($features);
174
175
                                // Go ahead and stash it since it's built already
176
                                $this->integrations[$integrationName]->setIntegrationSettings($newIntegration);
177
178
                                $newIntegrations[] = $newIntegration;
179
180
                                unset($newIntegration);
181
                            } else {
182
                                /**
183
                                 * @deprecated: 2.8.2 To be removed in 3.0
184
                                 *            This keeps BC for 3rd party plugins
185
                                 */
186
                                $class    = '\\MauticPlugin\\'.$pluginNamespace.'\\Integration\\'.$integrationName.'Integration';
187
                                $refClass = new \ReflectionClass($class);
188
189
                                if ($refClass->isInstantiable()) {
190
                                    $this->integrations[$integrationName] = new $class($this->factory);
0 ignored issues
show
Deprecated Code introduced by
The property Mautic\PluginBundle\Help...grationHelper::$factory has been deprecated: 2.8.2 To be removed in 3.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

190
                                    $this->integrations[$integrationName] = new $class(/** @scrutinizer ignore-deprecated */ $this->factory);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
191
                                    $features                             = $this->integrations[$integrationName]->getSupportedFeatures();
192
193
                                    $newIntegration->setSupportedFeatures($features);
194
195
                                    // Go ahead and stash it since it's built already
196
                                    $this->integrations[$integrationName]->setIntegrationSettings($newIntegration);
197
198
                                    $newIntegrations[] = $newIntegration;
199
200
                                    unset($newIntegration);
201
                                } else {
202
                                    // Something is bad so ignore
203
                                    continue;
204
                                }
205
                            }
206
                        }
207
208
                        /** @var \Mautic\PluginBundle\Entity\Integration $settings */
209
                        $settings                          = $integrationSettings[$integrationName];
210
                        $this->available[$integrationName] = [
211
                            'isPlugin'    => true,
212
                            'integration' => $integrationName,
213
                            'settings'    => $settings,
214
                            'namespace'   => $pluginNamespace,
215
                        ];
216
217
                        // Sort by feature and plugin for later
218
                        $features = $settings->getSupportedFeatures();
219
                        foreach ($features as $feature) {
220
                            if (!isset($this->byFeatureList[$feature])) {
221
                                $this->byFeatureList[$feature] = [];
222
                            }
223
                            $this->byFeatureList[$feature][] = $integrationName;
224
                        }
225
                        $this->byPlugin[$id][] = $integrationName;
226
                    }
227
                }
228
            }
229
230
            $coreIntegrationSettings = $this->getCoreIntegrationSettings();
231
232
            // Scan core bundles for integration classes
233
            foreach ($this->bundleHelper->getMauticBundles() as $coreBundle) {
234
                if (
235
                    // Skip plugin bundles
236
                    strpos($coreBundle['directory'], 'app/bundles') !== false
237
                    // Skip core bundles without an Integration directory
238
                    && is_dir($coreBundle['directory'].'/Integration')
239
                ) {
240
                    $finder = new Finder();
241
                    $finder->files()->name('*Integration.php')->in($coreBundle['directory'].'/Integration')->ignoreDotFiles(true);
242
243
                    $coreBundleNamespace = str_replace('Mautic', '', $coreBundle['bundle']);
244
245
                    foreach ($finder as $file) {
246
                        $integrationName = substr($file->getBaseName(), 0, -15);
247
248
                        if (!isset($coreIntegrationSettings[$integrationName])) {
249
                            $newIntegration = new Integration();
250
                            $newIntegration->setName($integrationName);
251
                            $integrationSettings[$integrationName] = $newIntegration;
252
253
                            $integrationContainerKey = strtolower("mautic.integration.{$integrationName}");
254
255
                            // Initiate the class in order to get the features supported
256
                            if ($this->container->has($integrationContainerKey)) {
257
                                $this->integrations[$integrationName] = $this->container->get($integrationContainerKey);
258
                                $features                             = $this->integrations[$integrationName]->getSupportedFeatures();
259
                                $newIntegration->setSupportedFeatures($features);
260
261
                                // Go ahead and stash it since it's built already
262
                                $this->integrations[$integrationName]->setIntegrationSettings($newIntegration);
263
264
                                $newIntegrations[] = $newIntegration;
265
                            } else {
266
                                continue;
267
                            }
268
                        }
269
270
                        /** @var \Mautic\PluginBundle\Entity\Integration $settings */
271
                        $settings                          = isset($coreIntegrationSettings[$integrationName]) ? $coreIntegrationSettings[$integrationName] : $newIntegration;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $newIntegration does not seem to be defined for all execution paths leading up to this point.
Loading history...
272
                        $this->available[$integrationName] = [
273
                            'isPlugin'    => false,
274
                            'integration' => $integrationName,
275
                            'settings'    => $settings,
276
                            'namespace'   => $coreBundleNamespace,
277
                        ];
278
                    }
279
                }
280
            }
281
282
            // Save newly found integrations
283
            if (!empty($newIntegrations)) {
284
                $integrationRepo->saveEntities($newIntegrations);
285
                unset($newIntegrations);
286
            }
287
        }
288
289
        // Ensure appropriate formats
290
        if ($specificIntegrations !== null && !is_array($specificIntegrations)) {
291
            $specificIntegrations = [$specificIntegrations];
292
        }
293
294
        if ($withFeatures !== null && !is_array($withFeatures)) {
295
            $withFeatures = [$withFeatures];
296
        }
297
298
        // Build the integrations wanted
299
        if (!empty($pluginFilter)) {
300
            // Filter by plugin
301
            $filteredIntegrations = $this->byPlugin[$pluginFilter];
302
        } elseif (!empty($specificIntegrations)) {
303
            // Filter by specific integrations
304
            $filteredIntegrations = $specificIntegrations;
305
        } else {
306
            // All services by default
307
            $filteredIntegrations = array_keys($this->available);
308
        }
309
310
        // Filter by features
311
        if (!empty($withFeatures)) {
312
            $integrationsWithFeatures = [];
313
            foreach ($withFeatures as $feature) {
314
                if (isset($this->byFeatureList[$feature])) {
315
                    $integrationsWithFeatures = $integrationsWithFeatures + $this->byFeatureList[$feature];
316
                }
317
            }
318
319
            $filteredIntegrations = array_intersect($filteredIntegrations, $integrationsWithFeatures);
320
        }
321
322
        $returnServices = [];
323
324
        // Build the classes if not already
325
        foreach ($filteredIntegrations as $integrationName) {
326
            if (!isset($this->available[$integrationName]) || ($publishedOnly && !$this->available[$integrationName]['settings']->isPublished())) {
327
                continue;
328
            }
329
330
            if (!isset($this->integrations[$integrationName])) {
331
                $integration             = $this->available[$integrationName];
332
                $integrationContainerKey = strtolower("mautic.integration.{$integrationName}");
333
334
                if ($this->container->has($integrationContainerKey)) {
335
                    $this->integrations[$integrationName] = $this->container->get($integrationContainerKey);
336
                    $this->integrations[$integrationName]->setIntegrationSettings($integration['settings']);
337
                } else {
338
                    /**
339
                     * @deprecated: 2.8.2 To be removed in 3.0
340
                     *            This keeps BC for 3rd party plugins
341
                     */
342
                    $rootNamespace = $integration['isPlugin'] ? '\\MauticPlugin\\' : '\\Mautic\\';
343
                    $class         = $rootNamespace.$integration['namespace'].'\\Integration\\'.$integrationName.'Integration';
344
                    $refClass      = new \ReflectionClass($class);
345
346
                    if ($refClass->isInstantiable()) {
347
                        $this->integrations[$integrationName] = new $class($this->factory);
348
349
                        $this->integrations[$integrationName]->setIntegrationSettings($integration['settings']);
350
                    } else {
351
                        // Something is bad so ignore
352
                        continue;
353
                    }
354
                }
355
            }
356
357
            $returnServices[$integrationName] = $this->integrations[$integrationName];
358
        }
359
360
        foreach ($returnServices as $key => $value) {
361
            if (!isset($value)) {
362
                unset($returnServices[$key]);
363
            }
364
        }
365
366
        foreach ($returnServices as $key => $value) {
367
            if (!isset($value)) {
368
                unset($returnServices[$key]);
369
            }
370
        }
371
372
        if (empty($alphabetical)) {
373
            // Sort by priority
374
            uasort($returnServices, function ($a, $b) {
375
                $aP = (int) $a->getPriority();
376
                $bP = (int) $b->getPriority();
377
378
                if ($aP === $bP) {
379
                    return 0;
380
                }
381
382
                return ($aP < $bP) ? -1 : 1;
383
            });
384
        } else {
385
            // Sort by display name
386
            uasort($returnServices, function ($a, $b) {
387
                $aName = $a->getDisplayName();
388
                $bName = $b->getDisplayName();
389
390
                return strcasecmp($aName, $bName);
391
            });
392
        }
393
394
        return $returnServices;
395
    }
396
397
    /**
398
     * Get a single integration object.
399
     *
400
     * @param $name
401
     *
402
     * @return AbstractIntegration|bool
403
     */
404
    public function getIntegrationObject($name)
405
    {
406
        $integrationObjects = $this->getIntegrationObjects($name);
407
408
        return ((isset($integrationObjects[$name]))) ? $integrationObjects[$name] : false;
409
    }
410
411
    /**
412
     * Gets a count of integrations.
413
     *
414
     * @param $plugin
415
     *
416
     * @return int
417
     */
418
    public function getIntegrationCount($plugin)
419
    {
420
        if (!is_array($plugin)) {
421
            $plugins = $this->coreParametersHelper->getParameter('plugin.bundles');
422
            if (array_key_exists($plugin, $plugins)) {
423
                $plugin = $plugins[$plugin];
424
            } else {
425
                // It doesn't exist so return 0
426
427
                return 0;
428
            }
429
        }
430
431
        if (is_dir($plugin['directory'].'/Integration')) {
432
            $finder = new Finder();
433
            $finder->files()->name('*Integration.php')->in($plugin['directory'].'/Integration')->ignoreDotFiles(true);
434
435
            return iterator_count($finder);
436
        }
437
438
        return 0;
439
    }
440
441
    /**
442
     * Returns popular social media services and regex URLs for parsing purposes.
443
     *
444
     * @param bool $find If true, array of regexes to find a handle will be returned;
445
     *                   If false, array of URLs with a placeholder of %handle% will be returned
446
     *
447
     * @return array
448
     *
449
     * @todo Extend this method to allow plugins to add URLs to these arrays
450
     */
451
    public function getSocialProfileUrlRegex($find = true)
452
    {
453
        if ($find) {
454
            //regex to find a match
455
            return [
456
                'twitter'  => "/twitter.com\/(.*?)($|\/)/",
457
                'facebook' => [
458
                    "/facebook.com\/(.*?)($|\/)/",
459
                    "/fb.me\/(.*?)($|\/)/",
460
                ],
461
                'linkedin'  => "/linkedin.com\/in\/(.*?)($|\/)/",
462
                'instagram' => "/instagram.com\/(.*?)($|\/)/",
463
                'pinterest' => "/pinterest.com\/(.*?)($|\/)/",
464
                'klout'     => "/klout.com\/(.*?)($|\/)/",
465
                'youtube'   => [
466
                    "/youtube.com\/user\/(.*?)($|\/)/",
467
                    "/youtu.be\/user\/(.*?)($|\/)/",
468
                ],
469
                'flickr' => "/flickr.com\/photos\/(.*?)($|\/)/",
470
                'skype'  => "/skype:(.*?)($|\?)/",
471
                'google' => "/plus.google.com\/(.*?)($|\/)/",
472
            ];
473
        } else {
474
            //populate placeholder
475
            return [
476
                'twitter'    => 'https://twitter.com/%handle%',
477
                'facebook'   => 'https://facebook.com/%handle%',
478
                'linkedin'   => 'https://linkedin.com/in/%handle%',
479
                'instagram'  => 'https://instagram.com/%handle%',
480
                'pinterest'  => 'https://pinterest.com/%handle%',
481
                'klout'      => 'https://klout.com/%handle%',
482
                'youtube'    => 'https://youtube.com/user/%handle%',
483
                'flickr'     => 'https://flickr.com/photos/%handle%',
484
                'skype'      => 'skype:%handle%?call',
485
                'googleplus' => 'https://plus.google.com/%handle%',
486
            ];
487
        }
488
    }
489
490
    /**
491
     * Get array of integration entities.
492
     *
493
     * @return mixed
494
     */
495
    public function getIntegrationSettings()
496
    {
497
        return $this->em->getRepository('MauticPluginBundle:Integration')->getIntegrations();
498
    }
499
500
    public function getCoreIntegrationSettings()
501
    {
502
        return $this->em->getRepository('MauticPluginBundle:Integration')->getCoreIntegrations();
503
    }
504
505
    /**
506
     * Get the user's social profile data from cache or integrations if indicated.
507
     *
508
     * @param \Mautic\LeadBundle\Entity\Lead $lead
509
     * @param array                          $fields
510
     * @param bool                           $refresh
511
     * @param string                         $specificIntegration
512
     * @param bool                           $persistLead
513
     * @param bool                           $returnSettings
514
     *
515
     * @return array
516
     */
517
    public function getUserProfiles($lead, $fields = [], $refresh = false, $specificIntegration = null, $persistLead = true, $returnSettings = false)
518
    {
519
        $socialCache     = $lead->getSocialCache();
520
        $featureSettings = [];
521
        if ($refresh) {
522
            //regenerate from integrations
523
            $now = new DateTimeHelper();
524
525
            //check to see if there are social profiles activated
526
            $socialIntegrations = $this->getIntegrationObjects($specificIntegration, ['public_profile', 'public_activity']);
527
528
            /* @var \MauticPlugin\MauticSocialBundle\Integration\SocialIntegration $sn */
529
            foreach ($socialIntegrations as $integration => $sn) {
530
                $settings        = $sn->getIntegrationSettings();
531
                $features        = $settings->getSupportedFeatures();
532
                $identifierField = $this->getUserIdentifierField($sn, $fields);
533
534
                if ($returnSettings) {
535
                    $featureSettings[$integration] = $settings->getFeatureSettings();
536
                }
537
538
                if ($identifierField && $settings->isPublished()) {
539
                    $profile = (!isset($socialCache[$integration])) ? [] : $socialCache[$integration];
540
541
                    //clear the cache
542
                    unset($profile['profile'], $profile['activity']);
543
544
                    if (in_array('public_profile', $features) && $sn->isAuthorized()) {
545
                        $sn->getUserData($identifierField, $profile);
546
                    }
547
548
                    if (in_array('public_activity', $features) && $sn->isAuthorized()) {
549
                        $sn->getPublicActivity($identifierField, $profile);
550
                    }
551
552
                    if (!empty($profile['profile']) || !empty($profile['activity'])) {
553
                        if (!isset($socialCache[$integration])) {
554
                            $socialCache[$integration] = [];
555
                        }
556
557
                        $socialCache[$integration]['profile']     = (!empty($profile['profile'])) ? $profile['profile'] : [];
558
                        $socialCache[$integration]['activity']    = (!empty($profile['activity'])) ? $profile['activity'] : [];
559
                        $socialCache[$integration]['lastRefresh'] = $now->toUtcString();
560
                    }
561
                } elseif (isset($socialCache[$integration])) {
562
                    //integration is now not applicable
563
                    unset($socialCache[$integration]);
564
                }
565
            }
566
567
            if ($persistLead && !empty($socialCache)) {
568
                $lead->setSocialCache($socialCache);
569
                $this->em->getRepository('MauticLeadBundle:Lead')->saveEntity($lead);
570
            }
571
        } elseif ($returnSettings) {
572
            $socialIntegrations = $this->getIntegrationObjects($specificIntegration, ['public_profile', 'public_activity']);
573
            foreach ($socialIntegrations as $integration => $sn) {
574
                $settings                      = $sn->getIntegrationSettings();
575
                $featureSettings[$integration] = $settings->getFeatureSettings();
576
            }
577
        }
578
579
        if ($specificIntegration) {
580
            return ($returnSettings) ? [[$specificIntegration => $socialCache[$specificIntegration]], $featureSettings]
581
                : [$specificIntegration => $socialCache[$specificIntegration]];
582
        }
583
584
        return ($returnSettings) ? [$socialCache, $featureSettings] : $socialCache;
585
    }
586
587
    /**
588
     * @param      $lead
589
     * @param bool $integration
590
     *
591
     * @return array
592
     */
593
    public function clearIntegrationCache($lead, $integration = false)
594
    {
595
        $socialCache = $lead->getSocialCache();
596
        if (!empty($integration)) {
597
            unset($socialCache[$integration]);
598
        } else {
599
            $socialCache = [];
600
        }
601
        $lead->setSocialCache($socialCache);
602
        $this->em->getRepository('MauticLeadBundle:Lead')->saveEntity($lead);
603
604
        return $socialCache;
605
    }
606
607
    /**
608
     * Gets an array of the HTML for share buttons.
609
     */
610
    public function getShareButtons()
611
    {
612
        static $shareBtns = [];
613
614
        if (empty($shareBtns)) {
615
            $socialIntegrations = $this->getIntegrationObjects(null, ['share_button'], true);
616
            $templating         = $this->templatingHelper->getTemplating();
617
618
            /**
619
             * @var string
620
             * @var \Mautic\PluginBundle\Integration\AbstractIntegration $details
621
             */
622
            foreach ($socialIntegrations as $integration => $details) {
623
                /** @var \Mautic\PluginBundle\Entity\Integration $settings */
624
                $settings = $details->getIntegrationSettings();
625
626
                $featureSettings = $settings->getFeatureSettings();
627
                $apiKeys         = $details->decryptApiKeys($settings->getApiKeys());
628
                $plugin          = $settings->getPlugin();
629
                $shareSettings   = isset($featureSettings['shareButton']) ? $featureSettings['shareButton'] : [];
630
631
                //add the api keys for use within the share buttons
632
                $shareSettings['keys']   = $apiKeys;
633
                $shareBtns[$integration] = $templating->render($plugin->getBundle().":Integration/$integration:share.html.php", [
634
                    'settings' => $shareSettings,
635
                ]);
636
            }
637
        }
638
639
        return $shareBtns;
640
    }
641
642
    /**
643
     * Loops through field values available and finds the field the integration needs to obtain the user.
644
     *
645
     * @param $integrationObject
646
     * @param $fields
647
     *
648
     * @return bool
649
     */
650
    public function getUserIdentifierField($integrationObject, $fields)
651
    {
652
        $identifierField = $integrationObject->getIdentifierFields();
653
        $identifier      = (is_array($identifierField)) ? [] : false;
654
        $matchFound      = false;
655
656
        $findMatch = function ($f, $fields) use (&$identifierField, &$identifier, &$matchFound) {
657
            if (is_array($identifier)) {
658
                //there are multiple fields the integration can identify by
659
                foreach ($identifierField as $idf) {
660
                    $value = (is_array($fields[$f]) && isset($fields[$f]['value'])) ? $fields[$f]['value'] : $fields[$f];
661
662
                    if (!in_array($value, $identifier) && strpos($f, $idf) !== false) {
663
                        $identifier[$f] = $value;
664
                        if (count($identifier) === count($identifierField)) {
665
                            //found enough matches so break
666
                            $matchFound = true;
667
                            break;
668
                        }
669
                    }
670
                }
671
            } elseif ($identifierField === $f || strpos($f, $identifierField) !== false) {
672
                $matchFound = true;
673
                $identifier = (is_array($fields[$f])) ? $fields[$f]['value'] : $fields[$f];
674
            }
675
        };
676
677
        $groups = ['core', 'social', 'professional', 'personal'];
678
        $keys   = array_keys($fields);
679
        if (count(array_intersect($groups, $keys)) !== 0 && count($keys) <= 4) {
680
            //fields are group
681
            foreach ($fields as $group => $groupFields) {
682
                $availableFields = array_keys($groupFields);
683
                foreach ($availableFields as $f) {
684
                    $findMatch($f, $groupFields);
685
686
                    if ($matchFound) {
687
                        break;
688
                    }
689
                }
690
            }
691
        } else {
692
            $availableFields = array_keys($fields);
693
            foreach ($availableFields as $f) {
694
                $findMatch($f, $fields);
695
696
                if ($matchFound) {
697
                    break;
698
                }
699
            }
700
        }
701
702
        return $identifier;
703
    }
704
705
    /**
706
     * Get the path to the integration's icon relative to the site root.
707
     *
708
     * @param $integration
709
     *
710
     * @return string
711
     */
712
    public function getIconPath($integration)
713
    {
714
        $systemPath  = $this->pathsHelper->getSystemPath('root');
715
        $bundlePath  = $this->pathsHelper->getSystemPath('bundles');
716
        $pluginPath  = $this->pathsHelper->getSystemPath('plugins');
717
        $genericIcon = $bundlePath.'/PluginBundle/Assets/img/generic.png';
718
719
        if (is_array($integration)) {
720
            // A bundle so check for an icon
721
            $icon = $pluginPath.'/'.$integration['bundle'].'/Assets/img/icon.png';
722
        } elseif ($integration instanceof Plugin) {
723
            // A bundle so check for an icon
724
            $icon = $pluginPath.'/'.$integration->getBundle().'/Assets/img/icon.png';
725
        } elseif ($integration instanceof AbstractIntegration) {
726
            return $integration->getIcon();
727
        }
728
729
        if (file_exists($systemPath.'/'.$icon)) {
730
            return $icon;
731
        }
732
733
        return $genericIcon;
734
    }
735
}
736