Completed
Push — console-installer ( e2b50d...6ce748 )
by Adam
22:30
created

SugarFeedDashlet::process()   F

Complexity

Conditions 38
Paths > 20000

Size

Total Lines 211
Code Lines 120

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 38
eloc 120
nc 40800
nop 1
dl 0
loc 211
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3
/*********************************************************************************
4
 * SugarCRM Community Edition is a customer relationship management program developed by
5
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6
 *
7
 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
8
 * Copyright (C) 2011 - 2016 Salesagility Ltd.
9
 *
10
 * This program is free software; you can redistribute it and/or modify it under
11
 * the terms of the GNU Affero General Public License version 3 as published by the
12
 * Free Software Foundation with the addition of the following permission added
13
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
14
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
15
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16
 *
17
 * This program is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
20
 * details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License along with
23
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
24
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25
 * 02110-1301 USA.
26
 *
27
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
28
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
29
 *
30
 * The interactive user interfaces in modified source and object code versions
31
 * of this program must display Appropriate Legal Notices, as required under
32
 * Section 5 of the GNU Affero General Public License version 3.
33
 *
34
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
35
 * these Appropriate Legal Notices must retain the display of the "Powered by
36
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
37
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
38
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
39
 ********************************************************************************/
40
41
42
require_once('include/Dashlets/DashletGeneric.php');
43
require_once('include/externalAPI/ExternalAPIFactory.php');
44
45
class SugarFeedDashlet extends DashletGeneric {
46
var $displayRows = 15;
47
48
var $categories;
49
50
var $userfeed_created;
51
52
var $selectedCategories = array();
53
54
55
    function __construct($id, $def = null) {
56
		global $current_user, $app_strings, $app_list_strings;
57
58
		require_once('modules/SugarFeed/metadata/dashletviewdefs.php');
59
		$this->myItemsOnly = false;
60
        parent::__construct($id, $def);
61
		$this->myItemsOnly = false;
62
		$this->isConfigurable = true;
63
		$this->hasScript = true;
64
		$pattern = array();
65
		$pattern[] = "/-/";
66
		$pattern[] = "/[0-9]/";
67
		$replacements = array();
68
		$replacements[] = '';
69
		$replacements[] = '';
70
		$this->idjs = preg_replace($pattern,$replacements,$this->id);
71
        // Add in some default categories.
72
        $this->categories['ALL'] = translate('LBL_ALL','SugarFeed');
73
        // Need to get the rest of the active SugarFeed modules
74
        $module_list = SugarFeed::getActiveFeedModules();
75
76
        // Translate the category names
77
        if ( ! is_array($module_list) ) { $module_list = array(); }
78
        foreach ( $module_list as $module ) {
79
            if ( $module == 'UserFeed' ) {
80
                // Fake module, need to translate specially
81
                $this->categories[$module] = translate('LBL_USER_FEED','SugarFeed');
82
            } else {
83
                $this->categories[$module] = $app_list_strings['moduleList'][$module];
84
            }
85
        }
86
87
        // Need to add the external api's here
88
        $this->externalAPIList = ExternalAPIFactory::getModuleDropDown('SugarFeed',true);
89
        if ( !is_array($this->externalAPIList) ) { $this->externalAPIList = array(); }
90
        foreach ( $this->externalAPIList as $apiObj => $apiName ) {
91
            $this->categories[$apiObj] = $apiName;
92
        }
93
94
95
        if(empty($def['title'])) $this->title = translate('LBL_HOMEPAGE_TITLE', 'SugarFeed');
96
		if(!empty($def['rows']))$this->displayRows = $def['rows'];
97
		if(!empty($def['categories']))$this->selectedCategories = $def['categories'];
98
		if(!empty($def['userfeed_created'])) $this->userfeed_created = $def['userfeed_created'];
99
        $this->searchFields = $dashletData['SugarFeedDashlet']['searchFields'];
100
        $this->columns = $dashletData['SugarFeedDashlet']['columns'];
101
102
        $twitter_enabled = $this->check_enabled('twitter');
103
        $facebook_enabled = $this->check_enabled('facebook');
104
105
        if($facebook_enabled){
106
            $this->categories["Facebook"] = "Facebook";
107
        }
108
109
        if($twitter_enabled){
110
            $this->categories["Twitter"] = "Twitter";
111
        }
112
113
		$catCount = count($this->categories);
114
		ACLController::filterModuleList($this->categories, false);
115
		if(count($this->categories) < $catCount){
116
			if(!empty($this->selectedCategories)){
117
				ACLController::filterModuleList($this->selectedCategories, true);
118
			}else{
119
				$this->selectedCategories = array_keys($this->categories);
120
				unset($this->selectedCategories[0]);
121
			}
122
		}
123
        $this->seedBean = new SugarFeed();
124
    }
125
126
    /**
127
     * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
128
     */
129
    function SugarFeedDashlet($id, $def = null){
130
        $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
131
        if(isset($GLOBALS['log'])) {
132
            $GLOBALS['log']->deprecated($deprecatedMessage);
133
        }
134
        else {
135
            trigger_error($deprecatedMessage, E_USER_DEPRECATED);
136
        }
137
        self::__construct($id, $def);
138
    }
139
140
	function process($lvsParams = array()) {
141
        global $current_user;
142
143
        $currentSearchFields = array();
144
        $configureView = true; // configure view or regular view
145
        $query = false;
146
        $whereArray = array();
147
        $lvsParams['massupdate'] = false;
148
149
        // apply filters
150
        if(isset($this->filters) || $this->myItemsOnly) {
151
            $whereArray = $this->buildWhere();
152
        }
153
154
        $this->lvs->export = false;
155
        $this->lvs->multiSelect = false;
156
		$this->lvs->quickViewLinks = false;
157
        // columns
158
    foreach($this->columns as $name => $val) {
159
                if(!empty($val['default']) && $val['default']) {
160
                    $displayColumns[strtoupper($name)] = $val;
161
                    $displayColumns[strtoupper($name)]['label'] = trim($displayColumns[strtoupper($name)]['label'], ':');
162
                }
163
            }
164
165
        $this->lvs->displayColumns = $displayColumns;
166
167
        $this->lvs->lvd->setVariableName($this->seedBean->object_name, array());
168
169
        $lvsParams['overrideOrder'] = true;
170
        $lvsParams['orderBy'] = 'date_entered';
171
        $lvsParams['sortOrder'] = 'DESC';
172
        $lvsParams['custom_from'] = '';
173
174
175
        // Get the real module list
176
        if (empty($this->selectedCategories)){
177
            $mod_list = $this->categories;
178
        } else {
179
            $mod_list = array_flip($this->selectedCategories);//27949, here the key of $this->selectedCategories is not module name, the value is module name, so array_flip it.
180
        }
181
182
        $external_modules = array();
183
        $admin_modules = array();
184
        $owner_modules = array();
185
        $regular_modules = array();
186
        foreach($mod_list as $module => $ignore) {
187
			// Handle the UserFeed differently
188
			if ( $module == 'UserFeed') {
189
				$regular_modules[] = 'UserFeed';
190
				continue;
191
			}
192
            if($module == 'Facebook'){
193
                $regular_modules[] = "Facebook";
194
                continue;
195
            }
196
            if($module == 'Twitter'){
197
                $regular_modules[] = 'Twitter';
198
                continue;
199
            }
200
201
            if ( in_array($module,$this->externalAPIList) ) {
202
                $external_modules[] = $module;
203
            }
204
			if (ACLAction::getUserAccessLevel($current_user->id,$module,'view') <= ACL_ALLOW_NONE ) {
205
				// Not enough access to view any records, don't add it to any lists
206
				continue;
207
			}
208
			if ( ACLAction::getUserAccessLevel($current_user->id,$module,'view') == ACL_ALLOW_OWNER ) {
209
				$owner_modules[] = $module;
210
            } else {
211
                $regular_modules[] = $module;
212
            }
213
        }
214
        //add custom modules here that will appear.
215
216
217
218
        if(!empty($this->displayTpl))
219
        {
220
        	//MFH BUG #14296
221
            $where = '';
222
            if(!empty($whereArray)){
223
                $where = '(' . implode(') AND (', $whereArray) . ')';
224
225
            }
226
227
            $additional_where = '';
228
229
230
			$module_limiter = " sugarfeed.related_module in ('" . implode("','", $regular_modules) . "')";
231
232
			if( is_admin($GLOBALS['current_user'] ) )
233
            {
234
                $all_modules = array_merge($regular_modules, $owner_modules, $admin_modules);
235
                $module_limiter = " sugarfeed.related_module in ('" . implode("','", $all_modules) . "')";
236
            }
237
            else if ( count($owner_modules) > 0
238
				) {
239
                $module_limiter = " ((sugarfeed.related_module IN ('".implode("','", $regular_modules)."') "
240
					.") ";
241
				if ( count($owner_modules) > 0 ) {
242
					$module_limiter .= "OR (sugarfeed.related_module IN('".implode("','", $owner_modules)."') AND sugarfeed.assigned_user_id = '".$current_user->id."' "
243
						.") ";
244
				}
245
				$module_limiter .= ")";
246
            }
247
			if(!empty($where)) { $where .= ' AND '; }
248
249
250
			$where .= $module_limiter;
251
252
            $this->lvs->setup($this->seedBean, $this->displayTpl, $where , $lvsParams, 0, $this->displayRows,
253
                              array('name',
254
                                    'description',
255
                                    'date_entered',
256
                                    'created_by',
257
                                    /* BEGIN - SECURITY GROUPS */
258
									//related_module now included but keep this here just in case
259
                                    'related_module',
260
                                    'related_id',
261
                                    /* END - SECURITY GROUPS */
262
263
264
265
266
                                    'link_url',
267
                                    'link_type'));
268
269
            foreach($this->lvs->data['data'] as $row => $data) {
270
271
                    $this->lvs->data['data'][$row]['NAME'] = str_replace("{this.CREATED_BY}",get_assigned_user_name($this->lvs->data['data'][$row]['CREATED_BY']),$data['NAME']);
272
273
                    //Translate the SugarFeeds labels if necessary.
274
                    preg_match('/\{([^\^ }]+)\.([^\}]+)\}/', $this->lvs->data['data'][$row]['NAME'] ,$modStringMatches );
275
                    if(count($modStringMatches) == 3 && $modStringMatches[1] == 'SugarFeed' && !empty($data['RELATED_MODULE']) )
276
                    {
277
                        $modKey = $modStringMatches[2];
278
                        $modString = translate($modKey, $modStringMatches[1]);
279
                        if( strpos($modString, '{0}') === FALSE || !isset($GLOBALS['app_list_strings']['moduleListSingular'][$data['RELATED_MODULE']]) )
280
                            continue;
281
282
                        $modStringSingular = $GLOBALS['app_list_strings']['moduleListSingular'][$data['RELATED_MODULE']];
283
                        $modString = string_format($modString, array($modStringSingular) );
284
                        $this->lvs->data['data'][$row]['NAME'] = preg_replace('/' . $modStringMatches[0] . '/', strtolower($modString), $this->lvs->data['data'][$row]['NAME']);
285
                    }
286
                //if social then unless the user is the assigned user it wont show. IJD1986
287
                if(($data['RELATED_MODULE'] == "facebook" || $data['RELATED_MODULE'] == "twitter" ) && $data['ASSIGNED_USER_ID'] != $current_user->id){
288
                    unset($this->lvs->data['data'][$row]);
289
                }
290
            }
291
292
            // assign a baseURL w/ the action set as DisplayDashlet
293
            foreach($this->lvs->data['pageData']['urls'] as $type => $url) {
294
            	// awu Replacing action=DisplayDashlet with action=DynamicAction&DynamicAction=DisplayDashlet
295
                $this->lvs->data['pageData']['urls'][$type] = $url.'&action=DynamicAction&DynamicAction=displayDashlet';
296
                if($type != 'orderBy')
297
                    $this->lvs->data['pageData']['urls'][$type] = $url.'&action=DynamicAction&DynamicAction=displayDashlet&sugar_body_only=1&id=' . $this->id;
298
            }
299
300
            $this->lvs->ss->assign('dashletId', $this->id);
301
302
303
        }
304
305
        $td = $GLOBALS['timedate'];
306
        $needResort = false;
307
        $resortQueue = array();
308
        $feedErrors = array();
309
310
        $fetchRecordCount = $this->displayRows + $this->lvs->data['pageData']['offsets']['current'];
311
312
        foreach ( $external_modules as $apiName ) {
313
            $api = ExternalAPIFactory::loadAPI($apiName);
314
            if ( $api !== FALSE ) {
315
                // FIXME: Actually calculate the oldest sugar feed we can see, once we get an API that supports this sort of filter.
316
                $reply = $api->getLatestUpdates(0,$fetchRecordCount);
317
                if ( $reply['success'] && count($reply['messages']) > 0 ) {
318
                    array_splice($resortQueue, count($resortQueue), 0, $reply['messages']);
319
                } else if ( !$reply['success'] ) {
320
                    $feedErrors[] = $reply['errorMessage'];
321
                }
322
            }
323
        }
324
325
        if ( count($feedErrors) > 0 ) {
326
            $this->lvs->ss->assign('feedErrors',$feedErrors);
327
        }
328
329
        // If we need to resort, get to work!
330
        foreach ( $this->lvs->data['data'] as $normalMessage ) {
331
            list($user_date,$user_time) = explode(' ',$normalMessage['DATE_ENTERED']);
332
            list($db_date,$db_time) = $td->to_db_date_time($user_date,$user_time);
333
334
            $unix_timestamp = strtotime($db_date.' '.$db_time);
335
336
            $normalMessage['sort_key'] = $unix_timestamp;
337
            $normalMessage['NAME'] = '</b>'.$normalMessage['NAME'];
338
339
            $resortQueue[] = $normalMessage;
340
        }
341
342
        usort($resortQueue,create_function('$a,$b','return $a["sort_key"]<$b["sort_key"];'));
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
343
344
        // Trim it down to the necessary number of records
345
        $numRecords = count($resortQueue);
346
        $numRecords = $numRecords - $this->lvs->data['pageData']['offsets']['current'];
347
        $numRecords = min($this->displayRows,$numRecords);
348
349
        $this->lvs->data['data'] = $resortQueue;
350
    }
351
352
	  function deleteUserFeed() {
353
    	if(!empty($_REQUEST['record'])) {
354
			$feed = new SugarFeed();
355
			$feed->retrieve($_REQUEST['record']);
356
			if(is_admin($GLOBALS['current_user']) || $feed->created_by == $GLOBALS['current_user']->id){
357
            	$feed->mark_deleted($_REQUEST['record']);
358
359
			}
360
        }
361
    }
362
	 function pushUserFeed() {
363
    	if(!empty($_REQUEST['text']) || (!empty($_REQUEST['link_url']) && !empty($_REQUEST['link_type']))) {
364
			$text = htmlspecialchars($_REQUEST['text']);
365
			//allow for bold and italic user tags
366
			$text = preg_replace('/&amp;lt;(\/*[bi])&amp;gt;/i','<$1>', $text);
367
            SugarFeed::pushFeed($text, 'UserFeed', $GLOBALS['current_user']->id,
368
								$GLOBALS['current_user']->id,
369
                                $_REQUEST['link_type'], $_REQUEST['link_url']
370
                                );
371
        }
372
373
    }
374
375
	 function pushUserFeedReply( ) {
376
         if(!empty($_REQUEST['text'])&&!empty($_REQUEST['parentFeed'])) {
377
			$text = htmlspecialchars($_REQUEST['text']);
378
			//allow for bold and italic user tags
379
			$text = preg_replace('/&amp;lt;(\/*[bi])&amp;gt;/i','<$1>', $text);
380
            SugarFeed::pushFeed($text, 'SugarFeed', $_REQUEST['parentFeed'],
381
								$GLOBALS['current_user']->id,
382
                                '', ''
383
                                );
384
        }
385
386
    }
387
388
	  function displayOptions() {
389
        global $app_strings;
390
        global $app_list_strings;
391
        $ss = new Sugar_Smarty();
392
        $ss->assign('titleLBL', translate('LBL_TITLE', 'SugarFeed'));
393
		$ss->assign('categoriesLBL', translate('LBL_CATEGORIES', 'SugarFeed'));
394
		$ss->assign('autenticationPendingLBL', translate('LBL_AUTHENTICATION_PENDING', 'SugarFeed'));
395
        $ss->assign('rowsLBL', translate('LBL_ROWS', 'SugarFeed'));
396
        $ss->assign('saveLBL', $app_strings['LBL_SAVE_BUTTON_LABEL']);
397
        $ss->assign('clearLBL', $app_strings['LBL_CLEAR_BUTTON_LABEL']);
398
        $ss->assign('title', $this->title);
399
		$ss->assign('categories', $this->categories);
400
        if ( empty($this->selectedCategories) ) {
401
            $this->selectedCategories['ALL'] = 'ALL';
402
        }
403
		$ss->assign('selectedCategories', $this->selectedCategories);
404
        $ss->assign('rows', $this->displayRows);
405
        $externalApis = array();
406
        foreach ( $this->externalAPIList as $apiObj => $apiName ) {
407
            //only show external APis that the user has not created
408
            if ( ! EAPM::getLoginInfo($apiName) ) {
409
                $externalApis[] = $apiObj;
410
            }
411
        }
412
        $ss->assign('externalApiList', JSON::encode($externalApis));
413
        $ss->assign('authenticateLBL', translate('LBL_AUTHENTICATE', 'SugarFeed'));
414
        $ss->assign('id', $this->id);
415
        if($this->isAutoRefreshable()) {
416
       		$ss->assign('isRefreshable', true);
417
			$ss->assign('autoRefresh', $GLOBALS['app_strings']['LBL_DASHLET_CONFIGURE_AUTOREFRESH']);
418
			$ss->assign('autoRefreshOptions', $this->getAutoRefreshOptions());
419
			$ss->assign('autoRefreshSelect', $this->autoRefresh);
420
		}
421
422
        return  $ss->fetch('custom/modules/SugarFeed/Dashlets/SugarFeedDashlet/Options.tpl');
423
    }
424
425
	/**
426
	 * creats the values
427
	 * @return
428
	 * @param $req Object
429
	 */
430
	  function saveOptions($req) {
431
        global $sugar_config, $timedate, $current_user, $theme;
432
        $options = array();
433
        $options['title'] = $req['title'];
434
		$rows = intval($_REQUEST['rows']);
435
        if($rows <= 0) {
436
            $rows = 15;
437
        }
438
		if($rows > 100){
439
			$rows = 100;
440
		}
441
        if ( isset($req['autoRefresh']) )
442
            $options['autoRefresh'] = $req['autoRefresh'];
443
        $options['rows'] = $rows;
444
		$options['categories'] = $req['categories'];
445
		foreach($options['categories'] as $cat){
446
			if($cat == 'ALL'){
447
				unset($options['categories']);
448
			}
449
		}
450
451
452
        return $options;
453
    }
454
455
456
      function sugarFeedDisplayScript() {
457
          // Forces the quicksearch to reload anytime the dashlet gets refreshed
458
          return '<script type="text/javascript">
459
enableQS(false);
460
</script>';
461
      }
462
	/**
463
	 *
464
	 * @return javascript including QuickSearch for SugarFeeds
465
	 */
466
	 function displayScript() {
467
	 	require_once('include/QuickSearchDefaults.php');
468
        $ss = new Sugar_Smarty();
469
        $ss->assign('saving', translate('LBL_SAVING', 'SugarFeed'));
470
        $ss->assign('saved', translate('LBL_SAVED', 'SugarFeed'));
471
        $ss->assign('id', $this->id);
472
        $ss->assign('idjs', $this->idjs);
473
474
        $str = $ss->fetch('modules/SugarFeed/Dashlets/SugarFeedDashlet/SugarFeedScript.tpl');
475
        return $str; // return parent::display for title and such
476
    }
477
478
	/**
479
	 *
480
	 * @return the fully rendered dashlet
481
	 */
482
	function display(){
483
484
		$listview = parent::display();
485
		$GLOBALS['current_sugarfeed'] = $this;
486
		$listview = preg_replace_callback('/\{([^\^ }]+)\.([^\}]+)\}/', create_function(
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
487
            '$matches',
488
            'if($matches[1] == "this"){$var = $matches[2]; return $GLOBALS[\'current_sugarfeed\']->$var;}else{return translate($matches[2], $matches[1]);}'
489
        ),$listview);
490
491
492
        //grab each token and store the module for later processing
493
        preg_match_all('/\[(\w+)\:/', $listview, $alt_modules);
494
495
        //now process each token to create the proper url and image tags in feed, leaving a string for the alt to be replaced in next step
496
		$listview = preg_replace('/\[(\w+)\:([\w\-\d]*)\:([^\]]*)\]/', '<a href="index.php?module=$1&action=DetailView&record=$2"><img src="themes/default/images/$1.gif" border=0 REPLACE_ALT>$3</a>', $listview); /*SKIP_IMAGE_TAG*/
497
498
499
        //process each module for the singular version so we can populate the alt tag on the image
500
        $altStrings = array();
501
        foreach($alt_modules[1] as $alt){
502
            //create the alt string and replace the alt token
503
            $altString = 'alt="'.translate('LBL_VIEW','SugarFeed').' '.$GLOBALS['app_list_strings']['moduleListSingular'][$alt].'"';
504
            $listview = preg_replace('/REPLACE_ALT/', $altString, $listview,1);
505
        }
506
507
508
509
510
		return $listview.'</div></div>';
511
	}
512
513
514
	/**
515
	 *
516
	 * @return the title and the user post form
517
	 * @param $text Object
518
	 */
519
	function getHeader($text='') {
520
		return parent::getHeader($text) . $this->getPostForm().$this->getDisabledWarning().$this->sugarFeedDisplayScript().'<div class="sugarFeedDashlet"><div id="contentScroller'.$this->idjs.'">';
521
	}
522
523
524
	/**
525
	 *
526
	 * @return a warning message if the sugar feed system is not enabled currently
527
	 */
528
	function getDisabledWarning(){
529
        /* Check to see if the sugar feed system is enabled */
530
        if ( ! $this->shouldDisplay() ) {
531
            // The Sugar Feeds are disabled, populate the warning message
532
            return translate('LBL_DASHLET_DISABLED','SugarFeed');
533
        } else {
534
            return '';
535
        }
536
    }
537
538
	/**
539
	 *
540
	 * @return the form for users posting custom messages to the feed stream
541
	 */
542
	function getPostForm(){
543
        global $current_user;
544
545
        if ( (!empty($this->selectedCategories) && !in_array('UserFeed',$this->selectedCategories))
546
			) {
547
            // The user feed system isn't enabled, don't let them post notes
548
            return '';
549
        }
550
		$user_name = ucfirst($GLOBALS['current_user']->user_name);
551
		$moreimg = SugarThemeRegistry::current()->getImage('advanced_search' , 'onclick="toggleDisplay(\'more_' . $this->id . '\'); toggleDisplay(\'more_img_'.$this->id.'\'); toggleDisplay(\'less_img_'.$this->id.'\');"',null,null,'.gif',translate('LBL_SHOW_MORE_OPTIONS','SugarFeed'));
552
		$lessimg = SugarThemeRegistry::current()->getImage('basic_search' , 'onclick="toggleDisplay(\'more_' . $this->id . '\'); toggleDisplay(\'more_img_'.$this->id.'\'); toggleDisplay(\'less_img_'.$this->id.'\');"',null,null,'.gif',translate('LBL_HIDE_OPTIONS','SugarFeed'));
553
		$ss = new Sugar_Smarty();
554
		$ss->assign('LBL_TO', translate('LBL_TO', 'SugarFeed'));
555
		$ss->assign('LBL_POST', translate('LBL_POST', 'SugarFeed'));
556
		$ss->assign('LBL_SELECT', translate('LBL_SELECT', 'SugarFeed'));
557
		$ss->assign('LBL_IS', translate('LBL_IS', 'SugarFeed'));
558
		$ss->assign('id', $this->id);
559
		$ss->assign('more_img', $moreimg);
560
		$ss->assign('less_img', $lessimg);
561
562
        include_once("include/social/get_feed_data.php");
563
        $ss->assign('facebook', $html );
564
565
        if($current_user->getPreference('use_real_names') == 'on'){
566
            $ss->assign('user_name', $current_user->full_name);
567
        }
568
        else {
569
            $ss->assign('user_name', $user_name);
570
        }
571
        $linkTypesIn = SugarFeed::getLinkTypes();
572
        $linkTypes = array();
573
        foreach ( $linkTypesIn as $key => $value ) {
0 ignored issues
show
Bug introduced by
The expression $linkTypesIn of type null|object<The>|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
574
            $linkTypes[$key] = translate('LBL_LINK_TYPE_'.$value,'SugarFeed');
575
        }
576
		$ss->assign('link_types', $linkTypes);
577
578
        $userPostFormTplFile = 'modules/SugarFeed/Dashlets/SugarFeedDashlet/UserPostForm.tpl';
579
        $fetch = $ss->fetch(get_custom_file_if_exists($userPostFormTplFile));
580
        return $fetch;
581
	}
582
583
    // This is called from the include/MySugar/DashletsDialog/DashletsDialog.php and determines if we should display the SugarFeed dashlet as an option or not
584
    static function shouldDisplay() {
585
586
        $admin = new Administration();
587
        $admin->retrieveSettings();
588
589
        if ( !isset($admin->settings['sugarfeed_enabled']) || $admin->settings['sugarfeed_enabled'] != '1' ) {
590
            return false;
591
        } else {
592
            return true;
593
        }
594
    }
595
596
    function check_enabled($type){
597
        global $db;
598
        $query = "SELECT * FROM config where name = 'module_" .$type . "' and value =  1;";
599
        $results = $db->query($query);
600
601
        while ($row = $db->fetchByAssoc($results)) {
602
            return true;
603
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
604
        }
605
    }
606
607
}
608