Exemplo n.º 1
0
 /**
  * Create new list from selection then mass add to newly created list
  */
 public function testExecute()
 {
     TestingAuxLib::suLogin('admin');
     X2List::model()->deleteAllByAttributes(array('name' => 'test'));
     $newList = new NewListFromSelection();
     $addToList = new MassAddToList();
     // create new list with 2 records
     $_POST['modelType'] = 'Contacts';
     $_POST['listName'] = 'test';
     $_SERVER['REQUEST_METHOD'] = 'POST';
     $_SERVER['SERVER_NAME'] = 'localhost';
     Yii::app()->controller = new ContactsController('contacts', new ContactsModule('contacts', null));
     $gvSelection = range(1, 2);
     AuxLib::debugLogR($newList->execute($gvSelection));
     $getFlashes = TestingAuxLib::setPublic('NewListFromSelection', 'getFlashes');
     AuxLib::debugLogR($getFlashes());
     $list = X2List::model()->findByAttributes(array('name' => 'test'));
     $itemIds = $list->queryCommand(true)->select('id')->queryColumn();
     $this->assertEquals(array(1, 2), $itemIds);
     //  add the rest of the contacts to the newly created list
     unset($_POST['modelType']);
     unset($_POST['listName']);
     $_POST['listId'] = $list->id;
     $gvSelection = range(3, 24);
     $addToList->execute($gvSelection);
     $itemIds = $list->queryCommand(true)->select('id')->queryColumn();
     $this->assertEquals(range(1, 24), $itemIds);
 }
Exemplo n.º 2
0
 /**
  * Clean up custom field columns 
  */
 public static function tearDownAfterClass()
 {
     $fields = Fields::model()->findAllByAttributes(array('custom' => 1));
     foreach ($fields as $field) {
         assert($field->delete());
     }
     Yii::app()->db->schema->refresh();
     Yii::app()->cache->flush();
     Contacts::model()->refreshMetaData();
     Contacts::model()->resetFieldsPropertyCache();
     AuxLib::debugLogR('Contacts::model ()->getAttributes () = ');
     AuxLib::debugLogR(Contacts::model()->getAttributes());
     parent::tearDownAfterClass();
 }
Exemplo n.º 3
0
 /**
  * Execute specified mass action on specified records
  */
 public function run()
 {
     if (Yii::app()->user->isGuest) {
         Yii::app()->controller->redirect(Yii::app()->controller->createUrl('/site/login'));
     }
     if (Yii::app()->request->getRequestType() === 'GET') {
         $_POST = $_GET;
     }
     if (isset($_POST['passConfirm']) && $_POST['passConfirm']) {
         MassAction::superMassActionPasswordConfirmation();
         return;
     }
     if (!isset($_POST['massAction']) || (!isset($_POST['superCheckAll']) || !$_POST['superCheckAll']) && (!isset($_POST['gvSelection']) || !is_array($_POST['gvSelection']))) {
         /**/
         AuxLib::debugLogR('run error');
         throw new CHttpException(400, Yii::t('app', 'Bad Request'));
     }
     $massAction = $_POST['massAction'];
     $massActionInstance = $this->getInstanceFor($massAction);
     if (isset($_POST['superCheckAll']) && $_POST['superCheckAll']) {
         $uid = $_POST['uid'];
         $idChecksum = $_POST['idChecksum'];
         $totalItemCount = intval($_POST['totalItemCount']);
         $massActionInstance->superExecute($uid, $totalItemCount, $idChecksum);
     } else {
         $gvSelection = $_POST['gvSelection'];
         $massActionInstance->beforeExecute();
         $massActionInstance->execute($gvSelection);
         $massActionInstance::echoFlashes();
     }
 }
Exemplo n.º 4
0
 public function read($label = '')
 {
     /**/
     AuxLib::debugLogR($label . round($this->endTime - $this->startTime, 2) . "\n");
     return $this;
 }
Exemplo n.º 5
0
 /**
  * Execute mass action on next batch of records
  * @param string $uid unique id
  * @param int $totalItemCount total number of records to operate on
  * @param string $expectedIdChecksum checksum of ids of records in data provider used to 
  *  generate the grid view
  */
 public function superExecute($uid, $totalItemCount, $expectedIdChecksum)
 {
     //$timer = new TimerUtil;
     //$timer->start ();
     // clear saved ids if user clicked the stop button
     if (isset($_POST['clearSavedIds']) && $_POST['clearSavedIds']) {
         if (!empty($uid)) {
             unset($_SESSION[self::SESSION_KEY_PREFIX . $uid]);
             unset($_SESSION[self::SESSION_KEY_PREFIX_PASS_CONFIRM . $uid]);
         }
         echo 'success';
         return;
     }
     // ensure that for super mass deletion, user confirmed deletion with password
     if ($this->requiresPasswordConfirmation && (empty($uid) || !isset($_SESSION[self::SESSION_KEY_PREFIX_PASS_CONFIRM . $uid]) || !$_SESSION[self::SESSION_KEY_PREFIX_PASS_CONFIRM . $uid])) {
         throw new CHttpException(401, Yii::t('app', 'You are not authorized to perform this action'));
     }
     if (!$this->requiresPasswordConfirmation && !empty($uid) && !isset($_SESSION[self::SESSION_KEY_PREFIX . $uid])) {
         /**/
         AuxLib::debugLogR('Error: $uid is not empty and SESSION key is not set');
         throw new CHttpException(400, Yii::t('app', 'Bad Request'));
     }
     $modelClass = Yii::app()->controller->modelClass;
     //$timer->stop ()->read ('first')->reset ()->start ();
     // if super mass operation hasn't started, initialize id list from which batches will
     // be retrieved
     if (empty($uid) || !isset($_SESSION[self::SESSION_KEY_PREFIX . $uid]) && $this->requiresPasswordConfirmation) {
         if (!$this->requiresPasswordConfirmation) {
             // removes the even the remote possibility of a key collision
             do {
                 $uid = uniqid(false, true);
             } while (isset($_SESSION[self::SESSION_KEY_PREFIX . $uid]));
         }
         list($ids, $idChecksum) = $this->getIdsFromSearchResults($modelClass);
         // This important check ensures that the number of records displayed in the grid view
         // is equal to the number of records filtered by the specified filters. This check
         // greatly reduces that chance of an incorrect update/deletion.
         if (count($ids) !== $totalItemCount || $idChecksum !== $expectedIdChecksum) {
             if (count($ids) !== $totalItemCount && $idChecksum !== $expectedIdChecksum) {
                 $errorCode = self::BAD_COUNT_AND_CHECKSUM;
             } else {
                 if (count($ids) !== $totalItemCount) {
                     $errorCode = self::BAD_ITEM_COUNT;
                 } else {
                     $errorCode = self::BAD_CHECKSUM;
                 }
             }
             echo CJSON::encode(array('failure' => true, 'errorMessage' => Yii::t('app', 'The data being displayed in this grid view is out of date. Close ' . 'this dialog and allow the grid to refresh before attempting this ' . 'mass action again.'), 'errorCode' => $errorCode));
             return;
         }
         $_SESSION[self::SESSION_KEY_PREFIX . $uid] = $ids;
     }
     //$timer->stop ()->read ('second')->reset ()->start ();
     // grab next batch of ids from session
     $selectedRecords = $_SESSION[self::SESSION_KEY_PREFIX . $uid];
     $selectedRecordsCount = count($selectedRecords);
     $batchSize = Yii::app()->settings->massActionsBatchSize;
     $batchSize = $selectedRecordsCount < $batchSize ? $selectedRecordsCount : $batchSize;
     $batch = array();
     for ($i = 0; $i < $batchSize; $i++) {
         // for efficiency reasons, record ids are stored in reverse order and popped.
         // array_shift = O(n), array_pop = O(1)
         $batch[] = array_pop($selectedRecords);
     }
     $_SESSION[self::SESSION_KEY_PREFIX . $uid] = $selectedRecords;
     // execute mass action on batch
     $successes = $this->execute($batch);
     // clear session once all batches have been completed
     if (count($selectedRecords) === 0) {
         unset($_SESSION[self::SESSION_KEY_PREFIX . $uid]);
         unset($_SESSION[self::SESSION_KEY_PREFIX_PASS_CONFIRM . $uid]);
     }
     $response = $this->generateSuperMassActionResponse($successes, $selectedRecords, $uid);
     //$timer->stop ()->read ('third')->reset ()->start ();
     echo CJSON::encode($response);
 }
Exemplo n.º 6
0
 /**
  * Prints stack trace 
  * @param int $limit If set, only the top $limit items on the call stack will get printed. 
  *  debug_backtrace does have an optional limit argument, but it wasn't introduced until php
  *  5.4.0.
  */
 public static function trace($limit = null)
 {
     if ($limit !== null) {
         /**/
         AuxLib::debugLogR(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, $limit));
     } else {
         /**/
         AuxLib::debugLogR(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
     }
 }
Exemplo n.º 7
0
 /**
  * Create a web lead form with a custom style
  *
  * Currently web forms have all options passed as GET parameters. Saved web forms
  * are saved to the table x2_web_forms. Saving, retrieving, and updating a web form
  * all happens in this function. Someday this should be updated to be it's own module.
  *
  * 
  * This get request is for weblead/service type only, marketing/weblist/view supplies 
  * the form that posts for weblist type 
  *  
  */
 public function run()
 {
     AuxLib::debugLogR($_POST);
     $modelClass = $this->controller->modelClass;
     if ($modelClass === 'Campaign') {
         $modelClass = 'Contacts';
     }
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         // save a web form
         if (empty($_POST['name'])) {
             if ($modelClass === 'Contacts') {
                 echo json_encode(array('errors' => array('name' => Yii::t('marketing', 'Name cannot be blank.'))));
             } elseif ($modelClass === 'Services') {
                 echo json_encode(array('errors' => array('name' => Yii::t('marketing', 'Name cannot be blank.'))));
             }
             return;
         }
         if ($modelClass === 'Contacts') {
             $type = !empty($_POST['type']) ? $_POST['type'] : 'weblead';
         } elseif ($modelClass === 'Services') {
             $type = 'serviceCase';
         }
         $model = WebForm::model()->findByAttributes(array('name' => $_POST['name'], 'type' => $type));
         // check if we are updating an existing web form
         if (!isset($model)) {
             $model = new WebForm();
             $model->name = $_POST['name'];
             $model->type = $type;
             $model->modelName = $modelClass;
             $model->visibility = 1;
             $model->assignedTo = Yii::app()->user->getName();
             $model->createdBy = Yii::app()->user->getName();
             $model->createDate = time();
         }
         //grab web lead configuration and stash in 'params'
         $whitelist = array('fg', 'bgc', 'font', 'bs', 'bc', 'tags');
         $config = array_filter(array_intersect_key($_POST, array_flip($whitelist)));
         //restrict param values, alphanumeric, # for color vals, comma for tag list
         $config = preg_replace('/[^a-zA-Z0-9#,]/', '', $config);
         if (!empty($config)) {
             $model->params = $config;
         } else {
             $model->params = null;
         }
         if (isset($_POST['generateLead']) && isset($_POST['leadSource'])) {
             $model->leadSource = $_POST['leadSource'];
             $model->generateLead = 1;
         } else {
             $model->generateLead = 0;
         }
         if (isset($_POST['generateAccount'])) {
             $model->generateAccount = 1;
         } else {
             $model->generateAccount = 0;
         }
         $model->updatedBy = Yii::app()->user->getName();
         $model->lastUpdated = time();
         if ($model->save()) {
             echo json_encode($model->attributes);
         } else {
             echo json_encode(array('errors' => $model->getErrors()));
         }
     } else {
         if ($modelClass === 'Contacts') {
             $criteria = X2Model::model('Marketing')->getAccessCriteria();
             $condition = $criteria->condition;
             $forms = WebForm::model()->findAll('type="weblead" AND ' . $condition, $criteria->params);
             $this->controller->render('application.modules.marketing.views.marketing.webleadForm', array('forms' => $forms));
         } else {
             if ($modelClass === 'Services') {
                 $criteria = X2Model::model('Services')->getAccessCriteria();
                 $condition = $criteria->condition;
                 // get service web forms (other option is 'weblead' used by marketing module)
                 $forms = WebForm::model()->findAll('type="serviceCase" AND ' . $condition, $criteria->params);
                 $this->controller->render('application.modules.services.views.services.createWebFormView', array('forms' => $forms));
             }
         }
     }
 }
 private function assertConversionCompatibility($record, $targetClass)
 {
     if (!$record->checkConversionCompatibility($targetClass)) {
         AuxLib::debugLogR('$record->getConversionCompatibilityWarnings ($targetClass) = ');
         AuxLib::debugLogR($record->getConversionIncompatibilityWarnings($targetClass));
         $this->assertTrue(false);
     }
 }
Exemplo n.º 9
0
 private function _flattenTrace($trace)
 {
     AuxLib::debugLogR('$trace = ');
     AuxLib::debugLogR($trace);
     if (!$trace[0]) {
         return false;
     }
     $flattenedTrace = array(array('action' => 'start', 'error' => !$trace[0]));
     $trace = $trace[1];
     while (true) {
         $complete = true;
         foreach ($trace as $action) {
             if ($action[0] === 'X2FlowSwitch') {
                 array_push($flattenedTrace, array('action' => $action[0], 'branch' => $action[1]));
                 $trace = $action[2];
                 $complete = false;
                 break;
             } else {
                 array_push($flattenedTrace, array('action' => $action[0], 'error' => !$action[1][0], 'message' => $action[1][1]));
             }
         }
         if ($complete) {
             break;
         }
     }
     return $flattenedTrace;
 }
Exemplo n.º 10
0
 /**
  * validates mass action name and returns MassAction instance that corresponds with it
  * @param string $massAction
  */
 private function getInstanceFor($massAction)
 {
     $instances = $this->getMassActionInstances();
     if (!in_array($massAction, array_keys($instances))) {
         /**/
         AuxLib::debugLogR('invalid mass action ' . $massAction);
         throw new CHttpException(400, Yii::t('app', 'Bad Request'));
     }
     return $instances[$massAction];
 }
Exemplo n.º 11
0
 public function requestTweets($append = false)
 {
     $this->getRateLimitStatus();
     $maxId = isset($_GET['maxTweetId']) ? $_GET['maxTweetId'] : -1;
     if (!isset($this->_tweets) || $append) {
         $username = $this->_username;
         $cache = Yii::app()->cache2;
         $cacheKey = $this->getCacheKey();
         $pageSize = 5;
         $tweets = $cache->get($cacheKey);
         if ($append && !$tweets) {
             // another page of tweets has been requested but the newer tweets have been
             // invalidated. To avoid having to determine how many pages down the user is,
             // we simply refresh the feed.
             $append = false;
         }
         if (!$tweets || $append) {
             // fetch tweets and add to cache
             if ($append) {
                 AuxLib::debugLogR('append');
             }
             $tweetCount = 100;
             $credentials = $this->getTwitterCredentials();
             $resourceName = '/statuses/user_timeline.json';
             $remainingRequests = $this->remainingRequests($resourceName);
             AuxLib::debugLogR('$remainingRequests = ');
             AuxLib::debugLogR($remainingRequests);
             if ($remainingRequests < 1) {
                 throw new CException('Rate limit met');
             }
             $url = 'https://api.twitter.com/1.1' . $resourceName;
             $getfield = '?screen_name=' . $username . '&count=' . $tweetCount;
             if ($append) {
                 $maxId = $tweets[count($tweets) - 1]['id_str'];
                 $getfield .= '&max_id=' . $maxId;
             }
             $requestMethod = 'GET';
             $twitter = new TwitterAPIExchange($credentials);
             $oldTweets = $tweets;
             $tweets = CJSON::decode($twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest());
             $this->remainingRequests($resourceName, $remainingRequests - 1);
             if ($append) {
                 $tweets = array_merge($oldTweets, $tweets);
             }
             $cache->set($cacheKey, $tweets, 60 * 5);
             AuxLib::debugLogR('cache miss');
         } else {
             AuxLib::debugLogR('cache hit');
         }
         if ($maxId === -1) {
             // initial page load, just return the first page
             $this->_tweets = array_slice($tweets, 0, $pageSize);
         } else {
             // max id specified, return all tweets up one page beyond max id
             $tweetCount = count($tweets);
             $found = false;
             for ($i = 0; $i < $tweetCount; $i++) {
                 $tweet = $tweets[$i];
                 if ($tweet['id_str'] == $maxId) {
                     $found = true;
                     break;
                 }
             }
             if ($found && $i + $pageSize < $tweetCount) {
                 $this->_tweets = array_slice($tweets, 0, $i + $pageSize + 1);
             } else {
                 if (!$append) {
                     // only request more tweets once
                     return $this->requestTweets(true);
                 } else {
                     // giving up on searching for specified tweet, just display the first page
                     $this->_tweets = array_slice($tweets, 0, $pageSize);
                 }
             }
         }
     }
     return $this->_tweets;
 }