2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
39 require_once('include/Dashlets/DashletGeneric.php');
40 require_once('include/externalAPI/ExternalAPIFactory.php');
42 class SugarFeedDashlet extends DashletGeneric {
43 var $displayRows = 15;
47 var $userfeed_created;
49 var $selectedCategories = array();
52 function SugarFeedDashlet($id, $def = null) {
53 global $current_user, $app_strings, $app_list_strings;
55 require('modules/SugarFeed/metadata/dashletviewdefs.php');
56 $this->myItemsOnly = false;
57 parent::DashletGeneric($id, $def);
58 $this->myItemsOnly = false;
59 $this->isConfigurable = true;
60 $this->hasScript = true;
63 $pattern[] = "/[0-9]/";
64 $replacements = array();
67 $this->idjs = preg_replace($pattern,$replacements,$this->id);
68 // Add in some default categories.
69 $this->categories['ALL'] = translate('LBL_ALL','SugarFeed');
70 // Need to get the rest of the active SugarFeed modules
71 $module_list = SugarFeed::getActiveFeedModules();
73 // Translate the category names
74 if ( ! is_array($module_list) ) { $module_list = array(); }
75 foreach ( $module_list as $module ) {
76 if ( $module == 'UserFeed' ) {
77 // Fake module, need to translate specially
78 $this->categories[$module] = translate('LBL_USER_FEED','SugarFeed');
80 $this->categories[$module] = $app_list_strings['moduleList'][$module];
84 // Need to add the external api's here
85 $this->externalAPIList = ExternalAPIFactory::getModuleDropDown('SugarFeed',true);
86 if ( !is_array($this->externalAPIList) ) { $this->externalAPIList = array(); }
87 foreach ( $this->externalAPIList as $apiObj => $apiName ) {
88 $this->categories[$apiObj] = $apiName;
92 if(empty($def['title'])) $this->title = translate('LBL_HOMEPAGE_TITLE', 'SugarFeed');
93 if(!empty($def['rows']))$this->displayRows = $def['rows'];
94 if(!empty($def['categories']))$this->selectedCategories = $def['categories'];
95 if(!empty($def['userfeed_created'])) $this->userfeed_created = $def['userfeed_created'];
96 $this->searchFields = $dashletData['SugarFeedDashlet']['searchFields'];
97 $this->columns = $dashletData['SugarFeedDashlet']['columns'];
98 $catCount = count($this->categories);
99 ACLController::filterModuleList($this->categories, false);
100 if(count($this->categories) < $catCount){
101 if(!empty($this->selectedCategories)){
102 ACLController::filterModuleList($this->selectedCategories, true);
104 $this->selectedCategories = array_keys($this->categories);
105 unset($this->selectedCategories[0]);
109 $this->seedBean = new SugarFeed();
112 function process($lvsParams = array()) {
113 global $current_user;
115 $currentSearchFields = array();
116 $configureView = true; // configure view or regular view
118 $whereArray = array();
119 $lvsParams['massupdate'] = false;
122 if(isset($this->filters) || $this->myItemsOnly) {
123 $whereArray = $this->buildWhere();
126 $this->lvs->export = false;
127 $this->lvs->multiSelect = false;
128 $this->lvs->quickViewLinks = false;
130 foreach($this->columns as $name => $val) {
131 if(!empty($val['default']) && $val['default']) {
132 $displayColumns[strtoupper($name)] = $val;
133 $displayColumns[strtoupper($name)]['label'] = trim($displayColumns[strtoupper($name)]['label'], ':');
137 $this->lvs->displayColumns = $displayColumns;
139 $this->lvs->lvd->setVariableName($this->seedBean->object_name, array());
141 $lvsParams['overrideOrder'] = true;
142 $lvsParams['orderBy'] = 'date_entered';
143 $lvsParams['sortOrder'] = 'DESC';
144 $lvsParams['custom_from'] = '';
147 // Get the real module list
148 if (empty($this->selectedCategories)){
149 $mod_list = $this->categories;
151 $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.
154 $external_modules = array();
155 $admin_modules = array();
156 $owner_modules = array();
157 $regular_modules = array();
158 foreach($mod_list as $module => $ignore) {
159 // Handle the UserFeed differently
160 if ( $module == 'UserFeed') {
161 $regular_modules[] = 'UserFeed';
164 if ( in_array($module,$this->externalAPIList) ) {
165 $external_modules[] = $module;
167 if (ACLAction::getUserAccessLevel($current_user->id,$module,'view') <= ACL_ALLOW_NONE ) {
168 // Not enough access to view any records, don't add it to any lists
171 if ( ACLAction::getUserAccessLevel($current_user->id,$module,'view') == ACL_ALLOW_OWNER ) {
172 $owner_modules[] = $module;
174 $regular_modules[] = $module;
178 if(!empty($this->displayTpl))
182 if(!empty($whereArray)){
183 $where = '(' . implode(') AND (', $whereArray) . ')';
187 $additional_where = '';
190 $module_limiter = " sugarfeed.related_module in ('" . implode("','", $regular_modules) . "')";
192 if( is_admin($GLOBALS['current_user'] ) )
194 $all_modules = array_merge($regular_modules, $owner_modules, $admin_modules);
195 $module_limiter = " sugarfeed.related_module in ('" . implode("','", $all_modules) . "')";
197 else if ( count($owner_modules) > 0
199 $module_limiter = " ((sugarfeed.related_module IN ('".implode("','", $regular_modules)."') "
201 if ( count($owner_modules) > 0 ) {
202 $module_limiter .= "OR (sugarfeed.related_module IN('".implode("','", $owner_modules)."') AND sugarfeed.assigned_user_id = '".$current_user->id."' "
205 $module_limiter .= ")";
207 if(!empty($where)) { $where .= ' AND '; }
210 $where .= $module_limiter;
212 $this->lvs->setup($this->seedBean, $this->displayTpl, $where , $lvsParams, 0, $this->displayRows,
221 foreach($this->lvs->data['data'] as $row => $data) {
223 $this->lvs->data['data'][$row]['NAME'] = str_replace("{this.CREATED_BY}",get_assigned_user_name($this->lvs->data['data'][$row]['ASSIGNED_USER_ID']),$data['NAME']);
227 // assign a baseURL w/ the action set as DisplayDashlet
228 foreach($this->lvs->data['pageData']['urls'] as $type => $url) {
229 // awu Replacing action=DisplayDashlet with action=DynamicAction&DynamicAction=DisplayDashlet
230 if($type == 'orderBy')
231 $this->lvs->data['pageData']['urls'][$type] = preg_replace('/(action=.*&)/Ui', 'action=DynamicAction&DynamicAction=displayDashlet&', $url);
233 $this->lvs->data['pageData']['urls'][$type] = preg_replace('/(action=.*&)/Ui', 'action=DynamicAction&DynamicAction=displayDashlet&', $url) . '&sugar_body_only=1&id=' . $this->id;
236 $this->lvs->ss->assign('dashletId', $this->id);
241 $td = $GLOBALS['timedate'];
243 $resortQueue = array();
244 $feedErrors = array();
246 $fetchRecordCount = $this->displayRows + $this->lvs->data['pageData']['offsets']['current'];
248 foreach ( $external_modules as $apiName ) {
249 $api = ExternalAPIFactory::loadAPI($apiName);
250 if ( $api !== FALSE ) {
251 // FIXME: Actually calculate the oldest sugar feed we can see, once we get an API that supports this sort of filter.
252 $reply = $api->getLatestUpdates(0,$fetchRecordCount);
253 if ( $reply['success'] && count($reply['messages']) > 0 ) {
254 array_splice($resortQueue, count($resortQueue), 0, $reply['messages']);
255 } else if ( !$reply['success'] ) {
256 $feedErrors[] = $reply['errorMessage'];
261 if ( count($feedErrors) > 0 ) {
262 $this->lvs->ss->assign('feedErrors',$feedErrors);
265 // If we need to resort, get to work!
266 foreach ( $this->lvs->data['data'] as $normalMessage ) {
267 list($user_date,$user_time) = explode(' ',$normalMessage['DATE_ENTERED']);
268 list($db_date,$db_time) = $td->to_db_date_time($user_date,$user_time);
270 $unix_timestamp = strtotime($db_date.' '.$db_time);
272 $normalMessage['sort_key'] = $unix_timestamp;
273 $normalMessage['NAME'] = '</b>'.$normalMessage['NAME'];
275 $resortQueue[] = $normalMessage;
278 usort($resortQueue,create_function('$a,$b','return $a["sort_key"]<$b["sort_key"];'));
280 // Trim it down to the necessary number of records
281 $numRecords = count($resortQueue);
282 $numRecords = $numRecords - $this->lvs->data['pageData']['offsets']['current'];
283 $numRecords = min($this->displayRows,$numRecords);
285 $this->lvs->data['data'] = $resortQueue;
288 function deleteUserFeed() {
289 if(!empty($_REQUEST['record'])) {
290 $feed = new SugarFeed();
291 $feed->retrieve($_REQUEST['record']);
292 if(is_admin($GLOBALS['current_user']) || $feed->created_by == $GLOBALS['current_user']->id){
293 $feed->mark_deleted($_REQUEST['record']);
298 function pushUserFeed() {
299 if(!empty($_REQUEST['text']) || (!empty($_REQUEST['link_url']) && !empty($_REQUEST['link_type']))) {
300 $text = htmlspecialchars($_REQUEST['text']);
301 //allow for bold and italic user tags
302 $text = preg_replace('/&lt;(\/*[bi])&gt;/i','<$1>', $text);
303 SugarFeed::pushFeed($text, 'UserFeed', $GLOBALS['current_user']->id,
304 $GLOBALS['current_user']->id,
305 $_REQUEST['link_type'], $_REQUEST['link_url']
311 function pushUserFeedReply( ) {
312 if(!empty($_REQUEST['text'])&&!empty($_REQUEST['parentFeed'])) {
313 $text = htmlspecialchars($_REQUEST['text']);
314 //allow for bold and italic user tags
315 $text = preg_replace('/&lt;(\/*[bi])&gt;/i','<$1>', $text);
316 SugarFeed::pushFeed($text, 'SugarFeed', $_REQUEST['parentFeed'],
317 $GLOBALS['current_user']->id,
324 function displayOptions() {
326 global $app_list_strings;
327 $ss = new Sugar_Smarty();
328 $ss->assign('titleLBL', translate('LBL_TITLE', 'SugarFeed'));
329 $ss->assign('categoriesLBL', translate('LBL_CATEGORIES', 'SugarFeed'));
330 $ss->assign('autenticationPendingLBL', translate('LBL_AUTHENTICATION_PENDING', 'SugarFeed'));
331 $ss->assign('rowsLBL', translate('LBL_ROWS', 'SugarFeed'));
332 $ss->assign('saveLBL', $app_strings['LBL_SAVE_BUTTON_LABEL']);
333 $ss->assign('title', $this->title);
334 $ss->assign('categories', $this->categories);
335 if ( empty($this->selectedCategories) ) {
336 $this->selectedCategories['ALL'] = 'ALL';
338 $ss->assign('selectedCategories', $this->selectedCategories);
339 $ss->assign('rows', $this->displayRows);
340 $externalApis = array();
341 foreach ( $this->externalAPIList as $apiObj => $apiName ) {
342 //only show external APis that the user has not created
343 if ( ! EAPM::getLoginInfo($apiName) ) {
344 $externalApis[] = $apiObj;
347 $ss->assign('externalApiList', JSON::encode($externalApis));
348 $ss->assign('authenticateLBL', translate('LBL_AUTHENTICATE', 'SugarFeed'));
349 $ss->assign('id', $this->id);
350 if($this->isAutoRefreshable()) {
351 $ss->assign('isRefreshable', true);
352 $ss->assign('autoRefresh', $GLOBALS['app_strings']['LBL_DASHLET_CONFIGURE_AUTOREFRESH']);
353 $ss->assign('autoRefreshOptions', $this->getAutoRefreshOptions());
354 $ss->assign('autoRefreshSelect', $this->autoRefresh);
357 return $ss->fetch('modules/SugarFeed/Dashlets/SugarFeedDashlet/Options.tpl');
365 function saveOptions($req) {
366 global $sugar_config, $timedate, $current_user, $theme;
368 $options['title'] = $req['title'];
369 $rows = intval($_REQUEST['rows']);
376 if ( isset($req['autoRefresh']) )
377 $options['autoRefresh'] = $req['autoRefresh'];
378 $options['rows'] = $rows;
379 $options['categories'] = $req['categories'];
380 foreach($options['categories'] as $cat){
382 unset($options['categories']);
391 function sugarFeedDisplayScript() {
392 // Forces the quicksearch to reload anytime the dashlet gets refreshed
393 return '<script type="text/javascript">
399 * @return javascript including QuickSearch for SugarFeeds
401 function displayScript() {
402 require_once('include/QuickSearchDefaults.php');
403 $ss = new Sugar_Smarty();
404 $ss->assign('saving', translate('LBL_SAVING', 'SugarFeed'));
405 $ss->assign('saved', translate('LBL_SAVED', 'SugarFeed'));
406 $ss->assign('id', $this->id);
407 $ss->assign('idjs', $this->idjs);
409 $str = $ss->fetch('modules/SugarFeed/Dashlets/SugarFeedDashlet/SugarFeedScript.tpl');
410 return $str; // return parent::display for title and such
415 * @return the fully rendered dashlet
419 $listview = parent::display();
420 $GLOBALS['current_sugarfeed'] = $this;
421 $listview = preg_replace_callback('/\{([^\^ }]+)\.([^\}]+)\}/', create_function(
423 'if($matches[1] == "this"){$var = $matches[2]; return $GLOBALS[\'current_sugarfeed\']->$var;}else{return translate($matches[2], $matches[1]);}'
425 $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>$3</a>', $listview);
427 return $listview.'</div></div>';
433 * @return the title and the user post form
434 * @param $text Object
436 function getHeader($text='') {
437 return parent::getHeader($text) . $this->getPostForm().$this->getDisabledWarning().$this->sugarFeedDisplayScript().'<div class="sugarFeedDashlet"><div id="contentScroller'.$this->idjs.'">';
443 * @return a warning message if the sugar feed system is not enabled currently
445 function getDisabledWarning(){
446 /* Check to see if the sugar feed system is enabled */
447 if ( ! $this->shouldDisplay() ) {
448 // The Sugar Feeds are disabled, populate the warning message
449 return translate('LBL_DASHLET_DISABLED','SugarFeed');
457 * @return the form for users posting custom messages to the feed stream
459 function getPostForm(){
460 global $current_user;
462 if ( (!empty($this->selectedCategories) && !in_array('UserFeed',$this->selectedCategories))
464 // The user feed system isn't enabled, don't let them post notes
467 $user_name = ucfirst($GLOBALS['current_user']->user_name);
468 $moreimg = SugarThemeRegistry::current()->getImage('advanced_search' , 'onclick="toggleDisplay(\'more_' . $this->id . '\'); toggleDisplay(\'more_img_'.$this->id.'\'); toggleDisplay(\'less_img_'.$this->id.'\');"');
469 $lessimg = SugarThemeRegistry::current()->getImage('basic_search' , 'onclick="toggleDisplay(\'more_' . $this->id . '\'); toggleDisplay(\'more_img_'.$this->id.'\'); toggleDisplay(\'less_img_'.$this->id.'\');"');
470 $ss = new Sugar_Smarty();
471 $ss->assign('LBL_TO', translate('LBL_TO', 'SugarFeed'));
472 $ss->assign('LBL_POST', translate('LBL_POST', 'SugarFeed'));
473 $ss->assign('LBL_SELECT', translate('LBL_SELECT', 'SugarFeed'));
474 $ss->assign('LBL_IS', translate('LBL_IS', 'SugarFeed'));
475 $ss->assign('id', $this->id);
476 $ss->assign('more_img', $moreimg);
477 $ss->assign('less_img', $lessimg);
478 if($current_user->getPreference('use_real_names') == 'on'){
479 $ss->assign('user_name', $current_user->full_name);
482 $ss->assign('user_name', $user_name);
484 $linkTypesIn = SugarFeed::getLinkTypes();
485 $linkTypes = array();
486 foreach ( $linkTypesIn as $key => $value ) {
487 $linkTypes[$key] = translate('LBL_LINK_TYPE_'.$value,'SugarFeed');
489 $ss->assign('link_types', $linkTypes);
490 return $ss->fetch('modules/SugarFeed/Dashlets/SugarFeedDashlet/UserPostForm.tpl');
494 // This is called from the include/MySugar/DashletsDialog/DashletsDialog.php and determines if we should display the SugarFeed dashlet as an option or not
495 static function shouldDisplay() {
497 $admin = new Administration();
498 $admin->retrieveSettings();
500 if ( !isset($admin->settings['sugarfeed_enabled']) || $admin->settings['sugarfeed_enabled'] != '1' ) {