Overview

Packages

  • application
    • commands
    • components
      • actions
      • filters
      • leftWidget
      • permissions
      • sortableWidget
      • util
      • webupdater
      • x2flow
        • actions
        • triggers
      • X2GridView
      • X2Settings
    • controllers
    • models
      • embedded
    • modules
      • accounts
        • controllers
        • models
      • actions
        • controllers
        • models
      • calendar
        • controllers
        • models
      • charts
        • models
      • contacts
        • controllers
        • models
      • docs
        • components
        • controllers
        • models
      • groups
        • controllers
        • models
      • marketing
        • components
        • controllers
        • models
      • media
        • controllers
        • models
      • mobile
        • components
      • opportunities
        • controllers
        • models
      • products
        • controllers
        • models
      • quotes
        • controllers
        • models
      • services
        • controllers
        • models
      • template
        • models
      • users
        • controllers
        • models
      • workflow
        • controllers
        • models
      • x2Leads
        • controllers
        • models
  • None
  • system
    • base
    • caching
    • console
    • db
      • ar
      • schema
    • validators
    • web
      • actions
      • auth
      • helpers
      • widgets
        • captcha
        • pagers
  • zii
    • widgets
      • grid

Classes

  • CalendarController
  • Overview
  • Package
  • Class
  • Tree
   1: <?php
   2: /*****************************************************************************************
   3:  * X2Engine Open Source Edition is a customer relationship management program developed by
   4:  * X2Engine, Inc. Copyright (C) 2011-2016 X2Engine Inc.
   5:  * 
   6:  * This program is free software; you can redistribute it and/or modify it under
   7:  * the terms of the GNU Affero General Public License version 3 as published by the
   8:  * Free Software Foundation with the addition of the following permission added
   9:  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  10:  * IN WHICH THE COPYRIGHT IS OWNED BY X2ENGINE, X2ENGINE DISCLAIMS THE WARRANTY
  11:  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  12:  * 
  13:  * This program is distributed in the hope that it will be useful, but WITHOUT
  14:  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  15:  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
  16:  * details.
  17:  * 
  18:  * You should have received a copy of the GNU Affero General Public License along with
  19:  * this program; if not, see http://www.gnu.org/licenses or write to the Free
  20:  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  21:  * 02110-1301 USA.
  22:  * 
  23:  * You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
  24:  * California 95067, USA. or at email address contact@x2engine.com.
  25:  * 
  26:  * The interactive user interfaces in modified source and object code versions
  27:  * of this program must display Appropriate Legal Notices, as required under
  28:  * Section 5 of the GNU Affero General Public License version 3.
  29:  * 
  30:  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
  31:  * these Appropriate Legal Notices must retain the display of the "Powered by
  32:  * X2Engine" logo. If the display of the logo is not reasonably feasible for
  33:  * technical reasons, the Appropriate Legal Notices must display the words
  34:  * "Powered by X2Engine".
  35:  *****************************************************************************************/
  36: 
  37: Yii::import('application.components.Ical');
  38: 
  39: /**
  40:  *  Calendar lets you create calendar events, view actions from other modules, and sync to google calendar.
  41:  *
  42:  * @property User $currentUser The currently logged-in user who is accessing the calendar
  43:  * @package application.modules.calendar.controllers
  44:  */
  45: class CalendarController extends x2base {
  46: 
  47:     private $_currentUser;
  48: 
  49:     public $modelClass = 'X2Calendar';
  50:     public $calendarUsers = null; // list of users for choosing whose calendar to view
  51:     public $groupCalendars = null;
  52:     public $sharedCalendars = null; // list of shared calendars to view/hide
  53:     public $googleCalendars = null;
  54:     public $calendarFilter = null;
  55: 
  56:     public function accessRules(){
  57:         return array(
  58:             array(
  59:                 'allow',
  60:                 'actions' => array('getItems'),
  61:                 'users' => array('*'),
  62:             ),
  63:             array(
  64:                 'allow', // allow authenticated user to perform 'create' and 'update' actions
  65:                 'actions' => array(
  66:                     'index',
  67:                     'jsonFeed',
  68:                     'jsonFeedGroup',
  69:                     'jsonFeedShared',
  70:                     'jsonFeedGoogle',
  71:                     'myCalendarPermissions',
  72:                     'create',
  73:                     'update',
  74:                     'list',
  75:                     'delete',
  76:                     'createEvent',
  77:                     'view',
  78:                     'viewAction',
  79:                     'editAction',
  80:                     'viewGoogleEvent',
  81:                     'editGoogleEvent',
  82:                     'moveAction',
  83:                     'moveGoogleEvent',
  84:                     'resizeAction',
  85:                     'resizeGoogleEvent',
  86:                     'saveAction',
  87:                     'saveGoogleEvent',
  88:                     'deleteGoogleEvent',
  89:                     'completeAction',
  90:                     'uncompleteAction',
  91:                     'deleteAction',
  92:                     'saveCheckedCalendar',
  93:                     'saveCheckedCalendarFilter',
  94:                     'syncActionsToGoogleCalendar',
  95:                     'toggleUserCalendarsVisible',
  96:                     'togglePortletVisible',
  97:                     //'uploadToGoogle'
  98:                 ),
  99:                 'users' => array('@'),
 100:             ),
 101:             array(
 102:                 'allow', // allow admin user to perform 'admin' and 'delete' actions
 103:                 'actions' => array('admin', 'userCalendarPermissions'),
 104:                 'users' => array('admin'),
 105:             ),
 106:             array(
 107:                 'deny', // deny all users
 108:                 'users' => array('*'),
 109:             ),
 110:         );
 111:     }
 112: 
 113:     /**
 114:      * Show Calendar
 115:      */
 116:     public function actionIndex(){
 117:         // Yii::app()->params->profile->syncAllEvents();
 118:         // $events = $this->feedAll(); // Submits prerendered list of events to the calendar.        
 119:         $this->initCheckedCalendars(); // ensure user has a list to save checked calendars
 120:         $this->render('calendar', array());
 121:     }
 122: 
 123:     /**
 124:      * Show Calendar
 125:      */
 126:     public function actionAdmin(){
 127:         $this->initCheckedCalendars(); // ensure user has a list to save checked calendars
 128:         $this->render('calendar');
 129:     }
 130: 
 131:     public function actionView($id){
 132:         if($id == 0)
 133:             $this->redirect(array('index'));
 134:         else{
 135:             $model = X2Calendar::model()->findByPk($id);
 136:             parent::view($model, 'calendar');
 137:         }
 138:     }
 139: 
 140:     
 141: 
 142:     /**
 143:      * Set who can view/edit current user's calendar
 144:      */
 145:     public function actionMyCalendarPermissions(){
 146: 
 147:         if(isset($_POST['save-button'])){
 148: 
 149:             // clear old permissions
 150:             X2CalendarPermissions::model()->deleteAllByAttributes(array('user_id' => Yii::app()->user->id));
 151: 
 152:             $viewPermission = array();
 153:             $editPermission = array();
 154: 
 155:             // $_POST['view-permission'] won't be set if no user has view permission
 156:             if(isset($_POST['view-permission'])){ // any users have permssion to view this user's calendar?
 157:                 $viewPermission = $_POST['view-permission'];
 158:             }
 159:             if(isset($_POST['edit-permission'])){ // any users have permssion to edit this user's calendar?
 160:                 $editPermission = $_POST['edit-permission'];
 161:             }
 162: 
 163:             $users = User::model()->findAll(array('select' => 'id'));
 164:             foreach($users as $user){
 165:                 $view = in_array($user->id, $viewPermission);
 166:                 $edit = in_array($user->id, $editPermission);
 167: 
 168:                 $permission = new X2CalendarPermissions;
 169:                 $permission->user_id = Yii::app()->user->id;
 170:                 $permission->other_user_id = $user->id;
 171:                 $permission->view = $view;
 172:                 $permission->edit = $edit;
 173:                 $permission->save();
 174:             }
 175:         }
 176: 
 177:         $this->render('myCalendarPermissions');
 178:         /*
 179:           $model = User::model()->findByPk(Yii::app()->user->id);
 180:           $users = User::getNames();
 181:           unset($users['Anyone']);
 182:           unset($users['admin']);
 183:           unset($users[Yii::app()->user->name]);
 184: 
 185:           if(isset($_POST['save-button'])) {
 186:           if(isset($_POST['User']['calendarViewPermission'])) {
 187:           $model->calendarViewPermission = $_POST['User']['calendarViewPermission'];
 188:           $model->calendarViewPermission = Fields::parseUsers($model->calendarViewPermission);
 189:           } else {
 190:           $model->calendarViewPermission = '';
 191:           }
 192: 
 193:           if(isset($_POST['User']['calendarEditPermission'])) {
 194:           $model->calendarEditPermission = $_POST['User']['calendarEditPermission'];
 195:           $model->calendarEditPermission = Fields::parseUsers($model->calendarEditPermission);
 196:           } else {
 197:           $model->calendarEditPermission = '';
 198:           }
 199: 
 200:           $model->setCalendarPermissions = true; // user has now set up calendar permissions
 201: 
 202:           $model->update();
 203:           $this->redirect(array('index'));
 204:           }
 205: 
 206:           $this->render('myCalendarPermissions', array('model'=>$model, 'users'=>$users)); */
 207:     }
 208: 
 209:     /**
 210:      *    Admin can set calendar permissions for all users
 211:      */
 212:     public function actionUserCalendarPermissions(){
 213:         if(isset($_POST['user-id'])){
 214:             $id = $_POST['user-id'];
 215: 
 216:             // clear old permissions
 217:             X2CalendarPermissions::model()->deleteAllByAttributes(array('user_id' => $id));
 218: 
 219:             $viewPermission = array();
 220:             $editPermission = array();
 221: 
 222:             // $_POST['view-permission'] won't be set if no user has view permission
 223:             if(isset($_POST['view-permission'])){ // any users have permssion to view this user's calendar?
 224:                 $viewPermission = $_POST['view-permission'];
 225:             }
 226:             if(isset($_POST['edit-permission'])){ // any users have permssion to edit this user's calendar?
 227:                 $editPermission = $_POST['edit-permission'];
 228:             }
 229: 
 230:             $users = User::model()->findAll(array('select' => 'id'));
 231:             foreach($users as $user){
 232:                 $view = in_array($user->id, $viewPermission);
 233:                 $edit = in_array($user->id, $editPermission);
 234: 
 235:                 $permission = new X2CalendarPermissions;
 236:                 $permission->user_id = $id;
 237:                 $permission->other_user_id = $user->id;
 238:                 $permission->view = $view;
 239:                 $permission->edit = $edit;
 240:                 $permission->save();
 241:             }
 242:         }
 243:         if(isset($_GET['id'])){
 244:             $this->render('userCalendarPermissions', array('id' => $_GET['id']));
 245:         }else{
 246:             $this->render('userCalendarPermissions');
 247:         }
 248:     }
 249: 
 250:     // overridden to disable parent method
 251:     public function actionQuickView ($id) {
 252:         echo Yii::t('app', 'Quick view not supported');
 253:     }
 254: 
 255:     /**
 256:      * Create shared calendar
 257:      */
 258:     public function actionCreate(){
 259: 
 260:         $model = new X2Calendar;
 261: 
 262:         if(isset($_POST['X2Calendar'])){
 263:             // copy $_POST data into Calendar model
 264: //            $this->render('test', array('model'=>$_POST));
 265:             foreach(array_keys($model->attributes) as $field){
 266:                 if(isset($_POST['X2Calendar'][$field])){
 267:                     $model->$field = $_POST['X2Calendar'][$field];
 268:                     $fieldData = Fields::model()->findByAttributes(array('modelName' => 'Calendar', 'fieldName' => $field));
 269:                     if(isset($fieldData) && $fieldData->type == 'assignment' && $fieldData->linkType == 'multiple'){
 270:                         $model->$field = Fields::parseUsers($model->$field);
 271:                     }elseif(isset($fieldData) && $fieldData->type == 'date'){
 272:                         $model->$field = strtotime($model->$field);
 273:                     }
 274:                 }
 275:             }
 276: 
 277:             if($model->googleCalendar && isset($_SESSION['token'])){
 278:                 $token = json_decode($_SESSION['token'], true);
 279:                 $model->googleRefreshToken = $token['refresh_token']; // used for accessing this google calendar at a later time
 280:                 $model->googleAccessToken = $_SESSION['token'];
 281:             }
 282: 
 283:             $model->createdBy = Yii::app()->user->name;
 284:             $model->updatedBy = Yii::app()->user->name;
 285:             $model->createDate = time();
 286:             $model->lastUpdated = time();
 287: 
 288:             $model->save();
 289:             $this->redirect(array('index'));
 290:         }
 291: 
 292:         $admin = Yii::app()->settings;
 293:         $googleIntegration = $admin->googleIntegration;
 294: 
 295:         // if google integration is activated let user choose if they want to link this calendar to a google calendar
 296: 
 297:         $credentials = Yii::app()->settings->getGoogleIntegrationCredentials ();
 298:         if($googleIntegration && $credentials){
 299:             require_once 'protected/integration/Google/google-api-php-client/src/Google/autoload.php';
 300: 
 301:             $client = new Google_Client();
 302:             $client->setApplicationName("Google Calendar Integration");
 303: 
 304:             // Visit https://code.google.com/apis/console?api=calendar to generate your
 305:             // client id, client secret, and to register your redirect uri.
 306:             $client->setClientId($credentials['clientId']);
 307:             $client->setClientSecret($credentials['clientSecret']);
 308:             $client->setRedirectUri((@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$this->createUrl(''));
 309:             //$client->setDeveloperKey($admin->googleAPIKey);
 310:             $client->setAccessType('offline');
 311:             $googleCalendar = new Google_Service_Calendar($client);
 312: 
 313:             if(isset($_GET['unlinkGoogleCalendar'])){ // user changed thier mind about linking their google calendar
 314:                 unset($_SESSION['token']);
 315:             }
 316: 
 317: 
 318:             if(isset($_GET['code'])){ // returning from google with access token
 319:                 $client->authenticate($_GET['code']);
 320:                 $_SESSION['token'] = $client->getAccessToken();
 321:                 header('Location: '.(@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
 322:             }
 323: 
 324:             if(isset($_SESSION['token'])){
 325:                 $client->setAccessToken($_SESSION['token']);
 326:                 $calList = $googleCalendar->calendarList->listCalendarList();
 327:                 $googleCalendarList = array();
 328:                 foreach($calList['items'] as $cal)
 329:                     $googleCalendarList[$cal['id']] = $cal['summary'];
 330:             }else{
 331:                 $googleCalendarList = null;
 332:             }
 333:         }else{
 334:             $client = null;
 335:             $googleCalendarList = null;
 336:         }
 337: 
 338:         $this->render('create', array('model' => $model,
 339:             'googleIntegration' => $googleIntegration,
 340:             'client' => $client,
 341:             'googleCalendarList' => $googleCalendarList,
 342:                 )
 343:         );
 344:     }
 345: 
 346:     /**
 347:      * update calendar with id $id
 348:      */
 349:     public function actionUpdate($id){
 350:         $model = $this->loadModel($id);
 351: 
 352:         if(isset($_POST['X2Calendar'])){
 353: 
 354:             // check for empty permissions
 355:             if(!isset($_POST['X2Calendar']['viewPermission']))
 356:                 $model->viewPermission = '';
 357:             if(!isset($_POST['X2Calendar']['editPermission']))
 358:                 $model->editPermission = '';
 359: 
 360:             // copy $_POST data into Calendar model
 361:             foreach(array_keys($model->attributes) as $field){
 362:                 if(isset($_POST['X2Calendar'][$field])){
 363:                     $model->$field = $_POST['X2Calendar'][$field];
 364:                     $fieldData = Fields::model()->findByAttributes(array('modelName' => 'Calendar', 'fieldName' => $field));
 365:                     if($fieldData->type == 'assignment' && $fieldData->linkType == 'multiple'){
 366:                         $model->$field = Fields::parseUsers($model->$field);
 367:                     }elseif($fieldData->type == 'date'){
 368:                         $model->$field = strtotime($model->$field);
 369:                     }
 370:                 }
 371:             }
 372: 
 373:             $model->updatedBy = Yii::app()->user->name;
 374:             $model->lastUpdated = time();
 375: 
 376:             $model->save();
 377:             $this->redirect(array('view', 'id' => $model->id));
 378:         }
 379: 
 380:         $admin = Yii::app()->settings;
 381:         $googleIntegration = $admin->googleIntegration;
 382: 
 383:         $this->render('update', array('model' => $model, 'googleIntegration' => $googleIntegration));
 384:     }
 385: 
 386:     public function actionList(){
 387:         $model = new X2Calendar('search');
 388:         $this->render('index', array('model' => $model));
 389:     }
 390: 
 391:     /**
 392:      * Delete shared Calendar
 393:      */
 394:     public function actionDelete($id){
 395:         $model = $this->loadModel($id);
 396:         $model->delete();
 397:         $this->redirect(array('list'));
 398:     }
 399: 
 400:     /*
 401:       Helper function for actionJsonFeed () and actionJsonFeedGroup ().
 402:       Returns:
 403:       A string containing a SQL boolean expression
 404:      */
 405:     private function constructFilterClause(array $filter){
 406:         $clause = "";
 407:         $clause .= "((complete != \"Yes\") "; // add incomplete actions
 408:         if(in_array('contacts', $filter))
 409:             $clause .= "OR (associationType = \"contacts\") "; // add contact actions
 410:         if(in_array('accounts', $filter))
 411:             $clause .= "OR (associationType = \"accounts\") "; // add account actions
 412:         if(in_array('opportunities', $filter))
 413:             $clause .= "OR (associationType = \"opportunities\") "; // add opportunities actions
 414:         if(in_array('quotes', $filter))
 415:             $clause .= "OR (associationType = \"quotes\") "; // add quote actions
 416:         if(in_array('products', $filter))
 417:             $clause .= "OR (associationType = \"product\") "; // add product actions
 418:         if(in_array('media', $filter))
 419:             $clause .= "OR (associationType = \"media\") "; // add media actions
 420:         if(in_array('completed', $filter))
 421:             $clause .= "OR (complete = \"Yes\") "; // add completed actions
 422:         $clause .= ")";
 423:         return $clause;
 424:     }
 425: 
 426:     /** 
 427:     * Retrieves a JSON of calendar events to send to the calendar view, which renders the events immediately
 428:     * @return - array of JSON strings
 429:     */
 430: 
 431:     /*public function actionJsonFeedAll($start=null, $end=null){
 432:             echo CJSON::encode($this->feedAll($start, $end));
 433:     }*/
 434: 
 435:     /**
 436:      * @param string $user username to fetch events for
 437:      * @param int    $start unix time to for start of window
 438:      * @param int    $end unix ending time
 439:      */
 440:     public function actionJsonFeed($user, $start, $end){
 441:         echo CJSON::encode($this->feedUser($user, $start, $end));
 442: 
 443:     }
 444: 
 445:     public function actionJsonFeedGroup($groupId, $start, $end){
 446:         echo CJSON::encode($this->feedGroup($groupId, $start, $end));
 447:     }
 448: 
 449:     public function actionJsonFeedGoogle($calendarId){
 450:         echo CJSON::encode($this->feedGoogle($calendarId));
 451:     }
 452: 
 453:     public function formatActionToEvent($action, $id){
 454:         if( !($action->visibility >= 1 || // don't show private actions,
 455:                 $action->assignedTo == Yii::app()->user->name ||  // unless they belong to current user
 456:                 Yii::app()->params->isAdmin) ) // admin sees all
 457:             return false;
 458: 
 459: 
 460:         $linked = !empty($action->associationType) && 
 461:             strtolower($action->associationType) != 'none' && 
 462:             class_exists(X2Model::getModelName($action->associationType));
 463:         if ($linked) {
 464:             $associatedModel = X2Model::getMOdelOfTypeWithId (
 465:                 X2Model::getModelName($action->associationType), $action->associationId);
 466:             if ($associatedModel) {
 467:                 $associationUrl = $associatedModel->getUrl ();
 468:             } else {
 469:                 $associationUrl = '';
 470:             }
 471:         }
 472:         
 473:         $title = $action->shortActionText;
 474: 
 475:         //Email formatting
 476:         $title = preg_replace('/<b>/', '', $title);
 477:         $title = preg_replace('/<\/b>/', '', $title);
 478:         $title = preg_replace('/\n\n/', "\n", $title);
 479:         $title = preg_replace('/<!--EndSig-->/', '', $title);
 480:         $title = preg_replace('/<!--BeginOpenedEmail-->/', '', $title);
 481:         $title = preg_replace('/<!--BeginSignature-->/', '', $title);
 482: 
 483:         if(in_array($action->type, array(
 484:                 'email', 'emailFrom', 'email_quote', 'email_invoice', 'emailOpened',
 485:                 'emailOpened_quote', 'emailOpened_invoice'))){
 486:             $title = 'Email: '.$title;
 487:         }
 488: 
 489:         $event = array(
 490:             'title' => $title,
 491:             'description' => $title,
 492:             'start' => date('Y-m-d H:i', $action->dueDate),
 493:             'id' => $action->id,
 494:             'complete' => $action->complete,
 495:             'calendarAssignment' => $id,
 496:             'allDay' => false,
 497:         );
 498: 
 499:         if($action->allDay)
 500:             $event['allDay'] = $action->allDay;
 501: 
 502:         if($action->color) {
 503:             $event['color'] = $action->color;
 504:         } else {
 505:             $event['color'] = '#6389de';
 506:             // old default color
 507:             //$event['color'] = '#3a87ad';
 508:         }
 509: 
 510:         static $brightnesses = array ();
 511:         if (!isset ($brightnesses[$event['color']])) {
 512:             $brightnesses[$event['color']] = X2Color::getColorBrightness ($event['color']);
 513:         }
 514:         if ($brightnesses[$event['color']] < 115) {
 515:             $event['textColor'] = 'white';
 516:         }
 517: 
 518:         if($action->type == 'event'){
 519:             if($action->completeDate)
 520:                 $event['end'] = date('Y-m-d H:i', $action->completeDate);
 521: 
 522:             $event['type'] = 'event';
 523:             $event['associationType'] = $action->associationType;
 524:         }
 525: 
 526:         $event['linked'] = $linked;
 527:         if($linked){
 528:             $event['associationType'] = $action->associationType;
 529:             $event['associationUrl'] = $associationUrl;
 530:             $event['associationName'] = $action->associationName;
 531:         }
 532:         
 533:         $editable = X2CalendarPermissions::getEditableUserCalendarNames();
 534:         // If it is a group id, we don't need to check this
 535:         $userEditable = !is_int($id) && isset($editable[$id]);
 536: 
 537:         $event['editable'] = $userEditable &&
 538:             Yii::app()->user->checkAccess('ActionsUpdate',array('X2Model'=>$action));
 539:         
 540:         return $event;
 541: 
 542:     }
 543: 
 544:     /** 
 545:      * Retrives all checked calendar events
 546:      * @param int $start starting unix time to fetch events between
 547:      * @param int $end ending unix time to fetch events between
 548:      */
 549: 
 550:     public function feedAll($start=null, $end=null){
 551: 
 552:         // default window is +/- one month
 553:         if(!isset($start))
 554:             $start = strtotime("-1 month");
 555:             $end = strtotime("+1 month");
 556: 
 557: 
 558:         $this->calendarUsers = X2CalendarPermissions::getViewableUserCalendarNames();
 559:         $this->groupCalendars = X2Calendar::getViewableGroupCalendarNames();
 560:         $this->calendarFilter = X2Calendar::getCalendarFilters();
 561: 
 562:         $user = User::model()->findByPk(Yii::app()->user->getId());
 563:         $showCalendars = json_decode($user->showCalendars, true);
 564: 
 565:         //fix showCalendars['groupCalendars']
 566:         if(!isset($showCalendars['groupCalendars'])){
 567:             $showCalendars['groupCalendars'] = array();
 568:             $user->showCalendars = json_encode($showCalendars);
 569:             $user->update();
 570:         }
 571: 
 572:         // get a list of all calendars to show
 573:         $events = array();
 574:         foreach($showCalendars['userCalendars'] as $cal){
 575:             $events = array_merge($events, $this->feedUser( $cal, $start, $end)); 
 576:         }
 577: 
 578:         foreach($showCalendars['groupCalendars'] as $cal){
 579:             $events = array_merge($events, $this->feedGroup( $cal, $start, $end)); 
 580:         }
 581: 
 582:         return $events;
 583:     }
 584: 
 585:     /**
 586:      * Fetches events assigned to a user between two timestamps
 587:      * @param string $user username to fetch events for 
 588:      * @param int $start UNIX timestamp for the beginning time 
 589:      * @param int $end UNIX timestamp for the end time
 590:      * @return array an array of fetched events
 591:      */
 592:     public function feedUser($user, $start, $end){
 593:         // These arent being used, but they look useful for something
 594:         // $loggedInUser = $this->currentUser; // User::model()->findByPk(Yii::app()->user->id); // get logged in user profile
 595:         // $filter = explode(',', $loggedInUser->calendarFilter); // action types user doesn't want filtered
 596:         // $possibleFilters = X2Calendar::getCalendarFilterNames(); // action types that can be filtered
 597: 
 598:         $actions = $this->calendarActions($user,$start,$end);
 599: 
 600:         $events = array();
 601:         foreach($actions as $action){
 602:             $event = $this->formatActionToEvent($action, $user);
 603: 
 604:             if($event)
 605:                 $events[] = $event;
 606:         }
 607: 
 608:         return $events;
 609:     }
 610: 
 611:     /**
 612:     * See {@link CalendarController::feedUser}
 613:     * @param int $groupId ID of the group assigned 
 614:     * @param int $start UNIX timestamp for the beginning time 
 615:     * @param int $end UNIX timestamp for the end time
 616:     * @return array An array of fetched events
 617:     */
 618:     public function feedGroup($groupId, $start, $end){
 619:         return $this->feedUser($groupId, $start, $end);
 620:     }
 621: 
 622:     /*public function actionUpdateGoogleEvents(){
 623:         Yii::app()->params->profile->fetchGoogleEvents();
 624:     }*/
 625: 
 626: 
 627:     // Deprecated, dont use.
 628:     public function feedGoogle($calendarId){
 629:         $calendar = X2Calendar::model()->findByPk($calendarId);
 630:         $events = array();
 631:         if($calendar->googleCalendarId){
 632:             $googleCalendar = $calendar->getGoogleCalendar();
 633:             $googleEvents = $googleCalendar->events->listEvents($calendar->googleCalendarId);
 634:             foreach($googleEvents['items'] as $googleEvent){
 635:                 $description = $googleEvent['summary'];
 636:                 if(isset($googleEvent['start']['dateTime'])){
 637:                     $allDay = false;
 638:                     $start = $googleEvent['start']['dateTime'];
 639:                     if(isset($googleEvent['end']['dateTime']))
 640:                         $end = $googleEvent['end']['dateTime'];
 641:                 } else{
 642:                     $allDay = true;
 643:                     $start = $googleEvent['start']['date'];
 644:                     if(isset($googleEvent['end']['date'])){
 645:                         $end = date("Y-m-d", strtotime($googleEvent['end']['date']) - 86400); // subtract a day because google saves all day events with one extra day
 646:                     }
 647:                 }
 648:                 $title = mb_substr($description, 0, 30, 'UTF-8');
 649:                 if(isset($googleEvent['colorId'])){
 650:                     $colorTable = array(
 651:                         10 => 'Green',
 652:                         11 => 'Red',
 653:                         6 => 'Orange',
 654:                         8 => 'Black',
 655:                     );
 656:                     if(isset($colorTable[$googleEvent['colorId']]))
 657:                         $color = $colorTable[$googleEvent['colorId']];
 658:                 }
 659:                 $events[] = array(
 660:                     'title' => $title,
 661:                     'id' => $googleEvent['id'],
 662:                     'description' => $description,
 663:                     'start' => $start,
 664:                     'allDay' => $allDay,
 665:                 );
 666:                 end($events);
 667:                 $last = key($events);
 668:                 if(isset($end))
 669:                     $events[$last]['end'] = $end;
 670:                 if(isset($color)){
 671:                     $events[$last]['color'] = $color;
 672:                     unset($color);
 673:                 }
 674:             }
 675:         }
 676: 
 677:         return $events;
 678:     }
 679: 
 680:     /**
 681:      *    Ajax requests call this function, which returns a form filled with the event data.
 682:      *  The form is then appended to a dialog in the users browser.
 683:      */
 684:     public function actionEditAction(){
 685:         if(isset($_POST['ActionId'])){ // ensure we are getting sane post data
 686:             $id = $_POST['ActionId'];
 687:             $model = Actions::model()->findByPk($id);
 688:             $isEvent = json_decode($_POST['IsEvent']);
 689: 
 690:             Yii::app()->clientScript->scriptMap['*.js'] = false;
 691:             Yii::app()->clientScript->scriptMap['*.css'] = false;
 692:             $this->renderPartial('editAction', array('model' => $model, 'isEvent' => $isEvent), false, true);
 693:         }
 694:     }
 695: 
 696:     /**
 697:      *    Ajax requests call this function, which returns read only action data.
 698:      *  The data is then appended to a dialog in the users browser.
 699:      */
 700:     public function actionViewAction(){
 701:         if(isset($_POST['ActionId'])){ // ensure we are getting sane post data
 702:             $id = $_POST['ActionId'];
 703:             $model = Actions::model()->findByPk($id);
 704:             $isEvent = json_decode($_POST['IsEvent']);
 705: 
 706:             Yii::app()->clientScript->scriptMap['*.js'] = false;
 707:             Yii::app()->clientScript->scriptMap['*.css'] = false;
 708:             $this->renderPartial(
 709:                 'viewAction',
 710:                 array(
 711:                     'model' => $model,
 712:                     'isEvent' => $isEvent
 713:                 ), false, true);
 714:         }
 715:     }
 716: 
 717:     public function actionViewGoogleEvent(){
 718:         if(isset($_POST['EventId']) && isset($_POST['CalendarId'])){
 719:             $eventId = $_POST['EventId'];
 720:             $calendarId = $_POST['CalendarId'];
 721:             $calendar = X2Calendar::model()->findByPk($calendarId);
 722:             $googleCalendar = $calendar->getGoogleCalendar();
 723:             $googleEvent = $googleCalendar->events->get($calendar->googleCalendarId, $eventId);
 724:             $model = new Actions;
 725:             $model->actionDescription = $googleEvent['summary'];
 726:             if(isset($googleEvent['start']['dateTime'])){
 727:                 $model->allDay = false;
 728:                 $model->dueDate = strtotime($googleEvent['start']['dateTime']);
 729:             }else{
 730:                 $model->allDay = true;
 731:                 $model->dueDate = strtotime($googleEvent['start']['date']);
 732:             }
 733:             if(isset($googleEvent['end']['dateTime']))
 734:                 $model->completeDate = strtotime($googleEvent['end']['dateTime']);
 735:             else
 736:                 $model->completeDate = strtotime($googleEvent['end']['date']);
 737: 
 738:             if(isset($googleEvent['colorId'])){
 739:                 $colorTable = array(
 740:                     10 => 'Green',
 741:                     11 => 'Red',
 742:                     6 => 'Orange',
 743:                     8 => 'Black',
 744:                 );
 745:                 if(isset($colorTable[$googleEvent['colorId']]))
 746:                     $model->color = $colorTable[$googleEvent['colorId']];
 747:             }
 748:             Yii::app()->clientScript->scriptMap['*.js'] = false;
 749:             Yii::app()->clientScript->scriptMap['*.css'] = false;
 750:             $this->renderPartial('viewGoogleEvent', array('model' => $model, 'eventId' => $eventId), false, true);
 751:         }
 752:     }
 753: 
 754:     public function actionEditGoogleEvent(){
 755:         if(isset($_POST['EventId']) && isset($_POST['CalendarId'])){
 756:             $eventId = $_POST['EventId'];
 757:             $calendarId = $_POST['CalendarId'];
 758:             $calendar = X2Calendar::model()->findByPk($calendarId);
 759: 
 760:             $googleCalendar = $calendar->getGoogleCalendar();
 761:             $googleEvent = $googleCalendar->events->get($calendar->googleCalendarId, $eventId);
 762:             $model = new Actions;
 763:             $model->actionDescription = $googleEvent['summary'];
 764:             if(isset($googleEvent['start']['dateTime'])){
 765:                 $model->allDay = false;
 766:                 $model->dueDate = strtotime($googleEvent['start']['dateTime']);
 767:             }else{
 768:                 $model->allDay = true;
 769:                 $model->dueDate = strtotime($googleEvent['start']['date']);
 770:             }
 771:             if(isset($googleEvent['end']['dateTime']))
 772:                 $model->completeDate = strtotime($googleEvent['end']['dateTime']);
 773:             else
 774:                 $model->completeDate = strtotime($googleEvent['end']['date']) - 86400;
 775: 
 776:             if(isset($googleEvent['colorId'])){
 777:                 $colorTable = array(
 778:                     10 => 'Green',
 779:                     11 => 'Red',
 780:                     6 => 'Orange',
 781:                     8 => 'Black',
 782:                 );
 783:                 if(isset($colorTable[$googleEvent['colorId']]))
 784:                     $model->color = $colorTable[$googleEvent['colorId']];
 785:             }
 786:             Yii::app()->clientScript->scriptMap['*.js'] = false;
 787:             Yii::app()->clientScript->scriptMap['*.css'] = false;
 788:             $this->renderPartial('editGoogleEvent', array('model' => $model, 'eventId' => $eventId), false, true);
 789:         }
 790:     }
 791: 
 792:     // move the start time of an action
 793:     // if the action has a complete date (or end date) it is also moved
 794:     public function actionMoveAction(){
 795:         if(isset($_POST['id'])){
 796:             $id = $_POST['id'];
 797:             $dayDelta = $_POST['dayChange']; // +/-
 798:             $minuteDelta = $_POST['minuteChange']; // +/-
 799:             $allDay = $_POST['isAllDay'];
 800: 
 801:             $action = Actions::model()->findByPk($id);
 802:             $action->allDay = (($allDay == 'true' || $allDay == 1) ? 1 : 0);
 803:             $action->dueDate += ($dayDelta * 86400) + ($minuteDelta * 60);
 804:             if($action->completeDate)
 805:                 $action->completeDate += ($dayDelta * 86400) + ($minuteDelta * 60);
 806: 
 807:             $profile = Profile::model()->findByAttributes(array('username' => $action->assignedTo));
 808:             if(isset($profile))
 809:                 $profile->updateGoogleCalendarEvent($action); // update action in Google Calendar if user has a Google Calendar
 810: 
 811:             if($action->save()){
 812:                 $event = X2Model::model('Events')->findByAttributes(array('associationType' => 'Actions', 'associationId' => $action->id));
 813:                 if(isset($event)){
 814:                     $event->timestamp = $action->dueDate;
 815:                     $event->save();
 816:                 }
 817:             }
 818:         }
 819:     }
 820: 
 821:     // move the time for a Google Calendar event
 822:     public function actionMoveGoogleEvent($calendarId){
 823:         if(isset($_POST['EventId'])){
 824:             $eventId = $_POST['EventId'];
 825:             $dayDelta = $_POST['dayChange']; // +/-
 826:             $minuteDelta = $_POST['minuteChange']; // +/-
 827:             $allDay = json_decode($_POST['isAllDay']);
 828:             $calendar = X2Calendar::model()->findByPk($calendarId);
 829:             $googleCalendar = $calendar->getGoogleCalendar();
 830:             $googleEvent = $googleCalendar->events->get($calendar->googleCalendarId, $eventId);
 831: 
 832:             if(isset($googleEvent['start']['dateTime'])){ // event was not all day
 833:                 $start = strtotime($googleEvent['start']['dateTime']);
 834:                 if($allDay){ // move event to all day
 835:                     unset($googleEvent['start']['dateTime']);
 836:                     $googleEvent['start']['date'] = date('Y-m-d', $start);
 837:                 }else{ // keep event as not all day
 838:                     $start += ($dayDelta * 86400) + ($minuteDelta * 60);
 839:                     $googleEvent['start']['dateTime'] = date('c', $start);
 840:                 }
 841:             }else{ // event was all day
 842:                 $start = strtotime($googleEvent['start']['date']);
 843:                 if($allDay){ // keep event as all day
 844:                     $start += ($dayDelta * 86400) + ($minuteDelta * 60);
 845:                     $googleEvent['start']['date'] = date('Y-m-d', $start);
 846:                 }else{ // move event to not all day
 847:                     unset($googleEvent['start']['date']);
 848:                     $start += ($dayDelta * 86400) + ($minuteDelta * 60);
 849:                     $googleEvent['start']['dateTime'] = date('c', $start);
 850:                 }
 851:             }
 852:             if(isset($googleEvent['end']['dateTime'])){ // event was not all day
 853:                 $end = strtotime($googleEvent['end']['dateTime']);
 854:                 if($allDay){ // move event to all day
 855:                     unset($googleEvent['end']['dateTime']);
 856:                     $end = strtotime($googleEvent['start']['date']) + 86400;
 857:                     $googleEvent['end']['date'] = date('Y-m-d', $end);
 858:                 }else{ // keep event as not all day
 859:                     $end += ($dayDelta * 86400) + ($minuteDelta * 60);
 860:                     $googleEvent['end']['dateTime'] = date('c', $end);
 861:                 }
 862:             }else if(isset($googleEvent['end']['date'])){ // event was all day
 863:                 $end = strtotime($googleEvent['end']['date']);
 864:                 if($allDay){ // keep event as all day
 865:                     $end += ($dayDelta * 86400) + ($minuteDelta * 60); // end = start + 1 day
 866:                     $googleEvent['end']['date'] = date('Y-m-d', $end);
 867:                 }else{ // move event to not all day
 868:                     unset($googleEvent['end']['date']);
 869:                     $end = strtotime($googleEvent['start']['dateTime']) + 7200; // end = start + 2 hours
 870:                     $googleEvent['end']['dateTime'] = date('c', $end);
 871:                 }
 872:             }
 873: 
 874:             $googleEvent = new Event($googleEvent);
 875:             $googleCalendar->events->update($calendar->googleCalendarId, $eventId, $googleEvent);
 876:         }
 877:     }
 878: 
 879:     // move the end (or complete) time of an action
 880:     // if the action doesn't have a
 881:     public function actionResizeAction(){
 882:         if(isset($_POST['id'])){
 883:             $id = $_POST['id'];
 884:             $dayDelta = $_POST['dayChange']; // +/-
 885:             $minuteDelta = $_POST['minuteChange']; // +/-
 886: 
 887:             $action = Actions::model()->findByPk($id);
 888:             if($action->completeDate) // actions without complete date aren't updated
 889:                 $action->completeDate += ($dayDelta * 86400) + ($minuteDelta * 60);
 890:             else if($action->type == 'event') // event without end date? give it one
 891:                 $action->completeDate = $action->dueDate + ($dayDelta * 86400) + ($minuteDelta * 60);
 892: 
 893:             $profile = Profile::model()->findByAttributes(array('username' => $action->assignedTo));
 894:             if(isset($profile))
 895:                 $profile->updateGoogleCalendarEvent($action); // update action in Google Calendar if user has a Google Calendar
 896: 
 897:             $action->save();
 898:         }
 899:     }
 900: 
 901:     // move the end time of a Google Calendar event
 902:     public function actionResizeGoogleEvent($calendarId){
 903:         if(isset($_POST['EventId'])){
 904:             $eventId = $_POST['EventId'];
 905:             $dayDelta = $_POST['dayChange']; // +/-
 906:             $minuteDelta = $_POST['minuteChange']; // +/-
 907:             $calendar = X2Calendar::model()->findByPk($calendarId);
 908:             $googleCalendar = $calendar->getGoogleCalendar();
 909:             $googleEvent = $googleCalendar->events->get($calendar->googleCalendarId, $eventId);
 910: 
 911:             if(isset($googleEvent['end']['dateTime'])){
 912:                 $end = strtotime($googleEvent['end']['dateTime']);
 913:                 $end += ($dayDelta * 86400) + ($minuteDelta * 60);
 914:                 $googleEvent['end']['dateTime'] = date('c', $end);
 915:             }else if(isset($googleEvent['end']['date'])){ // all day
 916:                 $end = strtotime($googleEvent['end']['date']);
 917:                 $end += ($dayDelta * 86400) + ($minuteDelta * 60);
 918:                 $googleEvent['end']['date'] = date('Y-m-d', $end);
 919:             }
 920: 
 921:             $googleEvent = new Event($googleEvent);
 922:             $googleCalendar->events->update($calendar->googleCalendarId, $eventId, $googleEvent);
 923:         }
 924:     }
 925: 
 926:     // save a actionDescription
 927:     public function actionSaveGoogleEvent($calendarId){
 928:         if(isset($_POST['EventId'])){
 929:             $eventId = $_POST['EventId'];
 930:             $calendar = X2Calendar::model()->findByPk($calendarId);
 931:             $googleCalendar = $calendar->getGoogleCalendar();
 932:             $googleEvent = $googleCalendar->events->get($calendar->googleCalendarId, $eventId);
 933: 
 934:             $model = new Actions;
 935:             foreach($model->attributes as $field => $value){
 936:                 if(isset($_POST['Actions'][$field])){
 937:                     $model->$field = $_POST['Actions'][$field];
 938:                 }
 939:             }
 940: 
 941:             if($model->allDay){
 942:                 $googleEvent['start']['date'] = date('Y-m-d', Formatter::parseDateTime($model->dueDate));
 943:                 if($model->completeDate)
 944:                     $googleEvent['end']['date'] = date('Y-m-d', Formatter::parseDateTime($model->completeDate) + 86400);
 945:                 if(isset($googleEvent['start']['dateTime']))
 946:                     unset($googleEvent['start']['dateTime']);
 947:                 if(isset($googleEvent['end']['dateTime']))
 948:                     unset($googleEvent['end']['dateTime']);
 949:             } else{
 950:                 $googleEvent['start']['dateTime'] = date('c', Formatter::parseDateTime($model->dueDate));
 951:                 if($model->completeDate)
 952:                     $googleEvent['end']['dateTime'] = date('c', Formatter::parseDateTime($model->completeDate));
 953:                 if(isset($googleEvent['start']['date']))
 954:                     unset($googleEvent['start']['date']);
 955:                 if(isset($googleEvent['end']['date']))
 956:                     unset($googleEvent['end']['date']);
 957:             }
 958: 
 959:             if($model->color && $model->color != '#3366CC'){
 960:                 $colorTable = array(
 961:                     10 => 'Green',
 962:                     11 => 'Red',
 963:                     6 => 'Orange',
 964:                     8 => 'Black',
 965:                 );
 966:                 if(($key = array_search($model->color, $colorTable)) != false)
 967:                     $googleEvent['colorId'] = $key;
 968:             }
 969: 
 970:             $googleEvent = new Event($googleEvent); // we send back a proper Event object to google
 971:             $googleEvent->setSummary($_POST['Actions']['actionDescription']);
 972:             $googleCalendar->events->update($calendar->googleCalendarId, $eventId, $googleEvent);
 973: //            $googleCalendar->events->delete($calendar->googleCalendarId, $eventId);
 974:         }
 975: 
 976: //        $this->render('test', array('model'=>$_POST));
 977:     }
 978: 
 979:     // save a actionDescription
 980:     public function actionDeleteGoogleEvent($calendarId){
 981:         if(isset($_POST['EventId'])){
 982:             $eventId = $_POST['EventId'];
 983:             $calendar = X2Calendar::model()->findByPk($calendarId);
 984:             $googleCalendar = $calendar->getGoogleCalendar();
 985:             $googleCalendar->events->delete($calendar->googleCalendarId, $eventId);
 986:         }
 987:     }
 988: 
 989:     // make an action complete
 990:     public function actionCompleteAction(){
 991:         if(isset($_POST['id'])){
 992:             $id = $_POST['id'];
 993: 
 994:             $action = Actions::model()->findByPk($id);
 995:             $action->complete = "Yes";
 996:             $action->completedBy = Yii::app()->user->getName();
 997:             $action->completeDate = time();
 998:             $action->update();
 999:         }
1000:     }
1001: 
1002:     // make an action uncomplete
1003:     public function actionUncompleteAction(){
1004:         if(isset($_POST['id'])){
1005:             $id = $_POST['id'];
1006: 
1007:             $action = Actions::model()->findByPk($id);
1008:             $action->complete = "No";
1009:             $action->completedBy = null;
1010:             $action->completeDate = null;
1011:             $action->update();
1012:         }
1013:     }
1014: 
1015:     // delete an action from the database
1016:     public function actionDeleteAction(){
1017:         if(isset($_POST['id'])){
1018:             $id = $_POST['id'];
1019: 
1020:             $action = Actions::model()->findByPk($id);
1021: 
1022:             $profile = Profile::model()->findByAttributes(array('username' => $action->assignedTo));
1023:             if(isset($profile))
1024:                 $profile->deleteGoogleCalendarEvent($action); // update action in Google Calendar if user has a Google Calendar
1025:             X2Model::model('Events')->deleteAllByAttributes(array('associationType' => 'Actions', 'type' => 'calendar_event', 'associationId' => $action->id));
1026:             $action->delete();
1027:         }
1028:     }
1029: 
1030:     // check if user profile has a list to remember which calendars the user has checked
1031:     // if not, create the list
1032:     public function initCheckedCalendars(){
1033:         $user = User::model()->findByPk(Yii::app()->user->getId());
1034:         // calendar list not initialized?
1035:         if($user->showCalendars == null)
1036:             $user->initCheckedCalendars();
1037:     }
1038: 
1039:     // if a user checked/unchecked a calendar, remember for the next to the user visits the page
1040:     public function actionSaveCheckedCalendar(){
1041:         if(isset($_POST['Calendar'])){
1042:             $calendar = $_POST['Calendar'];
1043:             $checked = $_POST['Checked'];
1044:             $type = $_POST['Type'];
1045:             $calendarType = $type.'Calendars';
1046: 
1047:             // get user list of checked calendars
1048:             $user = User::model()->findByPk(Yii::app()->user->getId());
1049:             $showCalendars = json_decode($user->showCalendars, true);
1050: 
1051:             if($checked)  // remember to show calendar
1052:                 if(!in_array($calendar, $showCalendars[$calendarType]))
1053:                     $showCalendars[$calendarType][] = $calendar;
1054:                 else // stop remembering to show calendar
1055:                 if(($key = array_search($calendar, $showCalendars[$calendarType])) !== false) // find calendar in list of shown calendars
1056:                     unset($showCalendars[$calendarType][$key]);
1057: 
1058:             /**/print_r($showCalendars);
1059:             $user->showCalendars = CJSON::encode($showCalendars);
1060:             $user->update();
1061:         }
1062:     }
1063: 
1064:     // when user checks/unchecks a filter, remember it in user profile
1065:     public function actionSaveCheckedCalendarFilter(){
1066:         if(isset($_POST['Filter'])){
1067:             $filterName = $_POST['Filter'];
1068:             $checked = $_POST['Checked'];
1069:             $user = User::model()->findByPk(Yii::app()->user->id);
1070:             $calendarFilter = explode(',', $user->calendarFilter);
1071: 
1072:             if($checked)
1073:                 if(!in_array($filterName, $calendarFilter))
1074:                     $calendarFilter[] = $filterName;
1075:                 else
1076:                 if(($key = array_search($filterName, $calendarFilter)) !== false)
1077:                     unset($calendarFilter[$key]);
1078: 
1079:             $user->calendarFilter = implode(',', $calendarFilter);
1080:             $user->update();
1081:         }
1082:     }
1083: 
1084:     /*public function actionUploadToGoogle(){
1085:         Yii::app()->params->profile->syncAllEvents();
1086:     }*/
1087: 
1088:     public function actionSyncActionsToGoogleCalendar(){
1089:         $errors = array();
1090:         $model = Yii::app()->params->profile;
1091:         $client = null;
1092:         if(isset($_POST['Profile'])){
1093:             foreach(array_keys($model->attributes) as $field){
1094:                 if(isset($_POST['Profile'][$field])){
1095:                     $model->$field = $_POST['Profile'][$field];
1096:                 }
1097:             }
1098: 
1099:             if($model->syncGoogleCalendarId && isset($_SESSION['token'])){
1100:                 $token = json_decode($_SESSION['token'], true);
1101:                 // used for accessing this google calendar at a later time
1102:                 //$model->syncGoogleCalendarRefreshToken = $token['refresh_token']; 
1103:                 $model->syncGoogleCalendarAccessToken = $_SESSION['token'];
1104:             }
1105: 
1106:             $model->update();
1107: 
1108:         }
1109: 
1110:         if(isset($_SESSION['calendarForceRefresh']) && $_SESSION['calendarForceRefresh']){
1111:             unset($_SESSION['calendarForceRefresh']);
1112:             Yii::app()->user->setFlash(
1113:                 'error',
1114:                 'Your Refresh Token was invalid and needed to be refreshed. The last action you ' .
1115:                 'attempted to Sync with Google did not successfully synchronize.');
1116:         }
1117:         $admin = Yii::app()->settings;
1118:         $googleIntegration = $admin->googleIntegration;
1119: 
1120:         /* if google integration is activated let user choose if they want to link this calendar 
1121:         to a google calendar */
1122:         if($googleIntegration){
1123: //            $timezone = date_default_timezone_get();
1124: //            require_once "protected/extensions/google-api-php-client/src/Google_Client.php";
1125: //            require_once "protected/extensions/google-api-php-client/src/contrib/Google_Service_Calendar.php"; // for google calendar sync
1126: //            require_once 'protected/extensions/google-api-php-client/src/contrib/Google_Service_Oauth2.php'; // for google oauth login
1127: //            date_default_timezone_set($timezone);
1128: 
1129:             $auth = new GoogleAuthenticator();
1130: 
1131:             /* name of the Google Calendar that current user's actions are being synced to if it 
1132:             has been set */
1133:             $syncGoogleCalendarName = null; 
1134:             try{
1135:                 if(isset($_GET['unlinkGoogleCalendar'])){ 
1136:                     // user changed their mind about linking their google calendar
1137: 
1138:                     unset($_SESSION['token']);
1139:                     $model->syncGoogleCalendarId = null;
1140:                     // used for accessing this google calendar at a later time
1141:                     //$model->syncGoogleCalendarRefreshToken = null; 
1142:                     $model->syncGoogleCalendarAccessToken = null;
1143:                     $model->update();
1144:                     $googleCalendarList = null;
1145:                     if($auth->getAccessToken()){
1146:                         $googleCalendar = $auth->getCalendarService();
1147:                         try{
1148:                             $calList = $googleCalendar->calendarList->listCalendarList();
1149:                             $googleCalendarList = array();
1150:                             foreach($calList['items'] as $cal){
1151:                                 $googleCalendarList[$cal['id']] = $cal['summary'];
1152:                             }
1153:                         }catch(Google_Service_Exception $e){
1154:                             if($e->getCode() == '403'){
1155:                                 $errors[] = $e->getMessage();
1156:                                 Yii::app()->user->setFlash('error', $e->getMessage());
1157:                                 $googleCalendarList = null;
1158:                                 //$auth->flushCredentials();
1159:                             }elseif($e->getCode() == '401'){
1160:                                 $errors[] = 'Invalid user credentials provided. Please try again.';
1161:                                 Yii::app()->user->setFlash(
1162:                                     'error',
1163:                                     'Invalid user credentials. Please ensure your account is ' . 
1164:                                     'able to use this service or delete the access permissions ' .
1165:                                     'and try again.');
1166:                                 $googleCalendarList = null;
1167:                                 $auth->flushCredentials();
1168:                             }
1169:                         }
1170:                     }else{
1171:                         $googleCalendarList = null;
1172:                     }
1173:                 }else{
1174:                     if($auth->getAccessToken()){
1175:                         $googleCalendar = $auth->getCalendarService();
1176:                         try{
1177:                             $calList = $googleCalendar->calendarList->listCalendarList();
1178:                             $googleCalendarList = array();
1179:                             foreach($calList['items'] as $cal){
1180:                                 $googleCalendarList[$cal['id']] = $cal['summary'];
1181:                             }
1182: 
1183: 
1184:                         }catch(Google_Service_Exception $e){
1185:                             if($e->getCode() == '403'){
1186:                                 $errors[] = 'Google Calendar API access has not been configured.';
1187:                                 Yii::app()->user->setFlash(
1188:                                     'error',
1189:                                     'Google Calendar API access has not been configured.');
1190:                                 $googleCalendarList = null;
1191:                                 //$auth->flushCredentials();
1192:                             }elseif($e->getCode() == '401'){
1193:                                 $errors[] = 'Invalid user credentials provided. Please try again.';
1194:                                 Yii::app()->user->setFlash(
1195:                                     'error',
1196:                                     'Invalid user credentials. Please ensure your account is ' .
1197:                                     'able to use this service or delete the access permissions ' .
1198:                                     'and try again.');
1199:                                 $googleCalendarList = null;
1200:                                 $auth->flushCredentials();
1201:                             }
1202:                         }
1203:                     }else{
1204:                         $googleCalendarList = null;
1205:                     }
1206:                 }
1207:             }catch(Google_Auth_Exception $e){
1208:                 $auth->flushCredentials();
1209:                 $auth->setErrors($e->getMessage());
1210:                 $client = null;
1211:                 $googleCalendarList = null;
1212:                 $syncGoogleCalendarName = null;
1213:             }
1214:         }else{
1215:             $client = null;
1216:             $googleCalendarList = null;
1217:             $syncGoogleCalendarName = null;
1218:         }
1219:         $syncGoogleCalendarId = Yii::app()->params->profile->syncGoogleCalendarId;   
1220: 
1221:         $this->render('syncActionsToGoogleCalendar', array(
1222:             'errors' => $errors,
1223:             'auth' => isset($auth) ? $auth : null,
1224:             'model' => $model,
1225:             'googleIntegration' => $googleIntegration,
1226:             'client' => $client,
1227:             'googleCalendarList' => $googleCalendarList,
1228:             'syncGoogleCalendarName' => $syncGoogleCalendarId,
1229:         ));
1230:     }
1231: 
1232:     public function actionToggleUserCalendarsVisible(){
1233:         echo Yii::app()->params->profile->userCalendarsVisible;
1234:     }
1235: 
1236:     public function actionTogglePortletVisible($portlet){
1237:         $parameterName = $portlet."Visible";
1238:         if(isset(Yii::app()->params->profile->$parameterName)){
1239:             $visible = Yii::app()->params->profile->$parameterName;
1240:             $visible = !$visible;
1241:             Yii::app()->params->profile->$parameterName = $visible;
1242:             Yii::app()->params->profile->update();
1243:             echo $visible;
1244:         }else{
1245:             echo 1; // if portlet not found, just make it visible
1246:         }
1247:     }
1248: 
1249:     /**
1250:      * Returns the data model based on the primary key given in the GET variable.
1251:      * If the data model is not found, an HTTP exception will be raised.
1252:      * @param integer the ID of the model to be loaded
1253:      */
1254:     public function loadModel($id){
1255:         $model = X2Calendar::model()->findByPk((int) $id);
1256:         if($model === null)
1257:             throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
1258:         return $model;
1259:     }
1260: 
1261:     /**
1262:      * Retrieve calendar events for a given user happening between two specified
1263:      * dates.
1264:      * @param string|integer $calendarUser Username or group ID whose calendar
1265:      *  events are to be loaded and returned
1266:      * @param type $start Beginning time range
1267:      * @param type $end End time range
1268:      * @param mixed $includePublic Set to 1 or boolean true to include all
1269:      *  calendar events 
1270:      * @return array An array of action records
1271:      */
1272:     public function calendarActions($calendarUser, $start, $end){
1273:         $filter = explode(',', $this->currentUser->calendarFilter); // action types user doesn't want filtered
1274:         $staticAction = Actions::model();
1275:         // View permissions for the viewing user
1276:         $criteria = $staticAction->getAccessCriteria();
1277:         // Assignment condition: all events for the user whose calendar is being viewed:
1278:         $criteria->addCondition('`assignedTo` REGEXP BINARY :unameRegex');
1279:         $permissionsBehavior = Yii::app()->params->modelPermissions;
1280:         $criteria->params[':unameRegex'] = $permissionsBehavior::getUserNameRegex($calendarUser);
1281:         // Action type filters:
1282:         $criteria->addCondition(self::constructFilterClause($filter));
1283:         $criteria->addCondition("`type` IS NULL OR `type`='' OR `type`='event'");
1284:         $criteria->addCondition('(`dueDate` >= :start1 AND `dueDate` <= :end1) '
1285:                 .'OR (`completeDate` >= :start2 AND `completeDate` <= :end2)');
1286:         $criteria->params = array_merge($criteria->params, array(
1287:             ':start1' => $start,
1288:             ':start2' => $start,
1289:             ':end1' => $end,
1290:             ':end2' => $end
1291:         ));
1292:         return Actions::model()->findAllWithoutActionText($criteria);
1293:     }
1294: 
1295:     /**
1296:      * Getter function for {@link $currentUser}
1297:      * @return type
1298:      */
1299:     public function getCurrentUser() {
1300:         if(!isset($this->_currentUser)) {
1301:             $this->_currentUser = User::model()->findByPk(Yii::app()->user->id);
1302:         }
1303:         return $this->_currentUser;
1304:     }
1305: 
1306:     /**
1307:      * Create a menu for the Calendar
1308:      * @param array Menu options to remove
1309:      * @param X2Model Model object passed to the view
1310:      * @param array Additional menu parameters
1311:      */
1312:     public function insertMenu($selectOptions = array(), $model = null, $menuParams = null) {
1313:         $Calendar = Modules::displayName();
1314:         $Actions = Modules::displayName(true, "Actions");
1315:         $User = Modules::displayName(false, "Users");
1316: 
1317:         /**
1318:          * To show all options:
1319:          * $menuOptions = array(
1320:          *     'index', 'myPermissions', 'userPermissions', 'sync',
1321:          * );
1322:          */
1323: 
1324:         $menuItems = array(
1325:             array(
1326:                 'name'=>'index',
1327:                 'label'=>Yii::t('calendar', '{calendar}', array('{calendar}'=>$Calendar)),
1328:                 'url'=>array('index')
1329:             ),
1330:             array(
1331:                 'name'=>'myPermissions',
1332:                 'label'=>Yii::t('calendar', 'My {calendar} Permissions', array(
1333:                     '{calendar}'=>$Calendar,
1334:                 )),
1335:                 'url'=>array('myCalendarPermissions')
1336:             ),
1337:             array(
1338:                 'name'=>'userPermissions',
1339:                 'label'=>Yii::t('calendar', '{user} {calendar} Permissions', array(
1340:                     '{calendar}'=>$Calendar,
1341:                     '{user}'=>$User,
1342:                 )),
1343:                 'url'=>array('userCalendarPermissions'),
1344:             ),
1345:             array(
1346:                 'name'=>'sync',
1347:                 'label'=>Yii::t('calendar', 'Sync My {actions} To Google Calendar', array(
1348:                     '{actions}' => $Actions,
1349:                 )),
1350:                 'url'=>array('syncActionsToGoogleCalendar'),
1351:             ),
1352:         );
1353: 
1354:         $this->prepareMenu($menuItems, $selectOptions);
1355:         $this->actionMenu = $this->formatMenu($menuItems, $menuParams);
1356:     }
1357: }
1358: 
X2CRM Documentation API documentation generated by ApiGen 2.8.0