function cassandra_query($sql)
{
    require_once 'phpcassa/connection.php';
    require_once 'phpcassa/columnfamily.php';
    $servers[0]['host'] = '127.0.0.1';
    $servers[0]['port'] = '9160';
    $conn = new Connection('Keyspace1', $servers);
    $sql_stmt = explode(" ", $sql);
    $cf = $sql_stmt[3];
    $uname = explode("=", $sql_stmt[5]);
    $passwd = explode("=", $sql_stmt[7]);
    echo $cf . " " . str_replace("'", "", $uname[1]) . " " . str_replace("'", "", $passwd[1]) . " " . $uname[0] . " " . $passwd[0];
    $column_family = new ColumnFamily($conn, $cf);
    echo $cf . " " . str_replace("'", "", $uname[1]) . " " . str_replace("'", "", $passwd[1]) . " " . $uname[0] . " " . $passwd[0];
    $index_exp = CassandraUtil::create_index_expression($uname[0], str_replace("'", "", $uname[1]));
    $index_clause = CassandraUtil::create_index_clause(array($index_exp));
    $rows = $column_family->get_indexed_slices($index_clause);
    foreach ($rows as $key => $columns) {
        if ($columns[$passwd[0]] == str_replace("'", "", $passwd[1])) {
            //			echo $columns;
            return $columns;
        } else {
            return NULL;
        }
    }
}
Пример #2
0
 public function actionRegister()
 {
     $formModel = new Registration();
     //$this->performAjaxValidation($formModel);
     if (isset($_POST['Registration'])) {
         $formModel->email = $_POST['Registration']['email'];
         $formModel->username = $_POST['Registration']['username'];
         $formModel->password = $_POST['Registration']['password'];
         $formModel->password_repeat = $_POST['Registration']['password_repeat'];
         $formModel->verification_code = $_POST['Registration']['verification_code'];
         if ($formModel->validate()) {
             $model = new User();
             if ($model->insert(CassandraUtil::uuid1(), array('email' => $_POST['Registration']['email'], 'username' => $_POST['Registration']['username'], 'password' => User::encryptPassword($_POST['Registration']['password']), 'active' => false, 'blocked' => false)) === true) {
                 echo 'Model email ' . $formModel->email . ' && username ' . $formModel->username;
                 if (!User::sendRegisterVerification($formModel->email, $formModel->username)) {
                     echo 'failed';
                 } else {
                     echo 'done';
                 }
                 die;
                 //$this->redirect(array('user/profile'));
             }
         }
     }
     $this->render('register', array('model' => $formModel));
 }
Пример #3
0
 /**
  * @param mixed $id
  * @return WeLearn_DTO_IDTO
  */
 public function remover($id)
 {
     if (!$id instanceof UUID) {
         $id = CassandraUtil::import($id);
     }
     $configuracaoRemovida = $this->recuperar($id);
     $this->_cf->remove($id->bytes);
     $configuracaoRemovida->setPersistido(false);
     return $configuracaoRemovida;
 }
 function __construct($uuid = null)
 {
     if (!isset($uuid)) {
         Loader::load("vendor", "phpcassa/columnfamily.php");
         $this->uuid = CassandraUtil::uuid1();
         //Loader::load("vendor","uuid/uuid");
         //		$this->uuid = UUID::TimeUUIDType();
         //		$this->uuid_binary = UUID::generate(UUID::UUID_TIME,UUID::FMT_BINARY);
         $this->data = new stdclass();
     } else {
         $this->uuid = $uuid;
     }
 }
Пример #5
0
 public function alterar($id)
 {
     try {
         $UUID = CassandraUtil::import($id);
         $categoriaDao = WeLearn_DAO_DAOFactory::create('CategoriaForumDAO');
         $categoria = $categoriaDao->recuperar($UUID);
         $this->_expulsarNaoAutorizados($categoria->getCurso());
         $dadosFormAlterar = array('nomeAtual' => $categoria->getNome(), 'descricaoAtual' => $categoria->getDescricao());
         $dadosViewAlterar = array('idCurso' => $categoria->getCurso()->getId(), 'formAction' => 'forum/categoria/salvar', 'extraOpenForm' => 'id="form-alterar-categoria-forum"', 'hiddenFormData' => array('categoriaId' => $categoria->getId(), 'acao' => 'alterar'), 'formAlterar' => $this->template->loadPartial('form', $dadosFormAlterar, 'curso/forum/categoria'), 'textoBotaoSubmit' => 'Salvar!');
         $this->_renderTemplateCurso($categoria->getCurso(), 'curso/forum/categoria/alterar', $dadosViewAlterar);
     } catch (Exception $e) {
         log_message('error', 'Erro ao exibir formulário de alteração de categoria de fórum:' . create_exception_description($e));
         show_404();
     }
 }
Пример #6
0
 function getEventsPageTagCloud($connection, $se)
 {
     $rowsFound = false;
     $sql = new ColumnFamily($connection, 'SOCIALEVENTTAG_SOCIALEVENT');
     $cloudquery = new ColumnFamily($connection, 'SOCIALEVENTTAG');
     $index_exp = CassandraUtil::create_index_expression('socialeventid', $se);
     $index_clause = CassandraUtil::create_index_clause(array($index_exp));
     $result = $sql->get_indexed_slices($index_clause);
     if (!empty($result)) {
         foreach ($result as $key => $value) {
             if ($value['socialeventtagid'] != NULL) {
                 $cloudresult = $cloudquery->get($value['socialeventtagid']);
                 if ($cloudresult['refcount'] > 0) {
                     $rowsFound = true;
                     $tags[$cloudresult['tag']] = $cloudresult['refcount'];
                 }
             }
         }
     }
     unset($cloudresult);
     if ($rowsFound) {
         // change these font sizes if you will
         $max_size = 250;
         // max font size in %
         $min_size = 100;
         // min font size in %
         // get the largest and smallest array values
         $max_count = max(array_values($tags));
         $min_count = min(array_values($tags));
         // find the range of values
         $spread = $max_count - $min_count;
         if (0 == $spread) {
             // we don't want to divide by zero
             $spread = 1;
         }
         // determine the font-size increment
         // this is the increase per tag count (times used)
         $step = ($max_size - $min_size) / $spread;
         // loop through our tag array
         foreach ($tags as $key => $value) {
             $size = $min_size + ($value - $min_count) * $step;
             // uncomment if you want sizes in whole %:
             $size = ceil($size);
             $eventTagCloud = $eventTagCloud . " " . '<a href="taggedEvents.php?tag=' . $key . '" style="font-size:' . $size . '%" title="' . $value . ' events tagged with ' . $key . '" >' . $key . '</a> ';
         }
     }
     return $eventTagCloud;
 }
Пример #7
0
 public function actionUpdate()
 {
     $formModel = new ProfileForm();
     if (isset($_POST['ProfileForm'])) {
         $allFieldTypes = $formModel->getAllFieldTypes();
         foreach ($allFieldTypes as $fieldName => $fieldType) {
             $formModel->{$fieldName} = $_POST['ProfileForm'][$fieldName];
         }
         if ($formModel->validate()) {
             $model = new Profile();
             $data = array();
             foreach ($allFieldTypes as $fieldName => $fieldType) {
                 $data[$fieldName] = array('value' => $formModel->{$fieldName});
             }
             $model->setProfileFields(CassandraUtil::import(Yii::app()->user->getId())->__toString(), User::PREFIX, $data);
         }
     }
     $this->render('update', array('model' => $formModel));
 }
Пример #8
0
 public function setUp()
 {
     $this->client = new Connection('Keyspace1');
     $this->cf_long = new ColumnFamily($this->client, 'StdLong');
     $this->cf_int = new ColumnFamily($this->client, 'StdInteger');
     $this->cf_time = new ColumnFamily($this->client, 'StdTimeUUID');
     $this->cf_lex = new ColumnFamily($this->client, 'StdLexicalUUID');
     $this->cf_ascii = new ColumnFamily($this->client, 'StdAscii');
     $this->cf_utf8 = new ColumnFamily($this->client, 'StdUTF8');
     $this->cf_suplong = new ColumnFamily($this->client, 'SuperLong');
     $this->cf_supint = new ColumnFamily($this->client, 'SuperInt');
     $this->cf_suptime = new ColumnFamily($this->client, 'SuperTime');
     $this->cf_suplex = new ColumnFamily($this->client, 'SuperLex');
     $this->cf_supascii = new ColumnFamily($this->client, 'SuperAscii');
     $this->cf_suputf8 = new ColumnFamily($this->client, 'SuperUTF8');
     $this->cf_suplong_sublong = new ColumnFamily($this->client, 'SuperLongSubLong');
     $this->cf_suplong_subint = new ColumnFamily($this->client, 'SuperLongSubInt');
     $this->cf_suplong_subtime = new ColumnFamily($this->client, 'SuperLongSubTime');
     $this->cf_suplong_sublex = new ColumnFamily($this->client, 'SuperLongSubLex');
     $this->cf_suplong_subascii = new ColumnFamily($this->client, 'SuperLongSubAscii');
     $this->cf_suplong_subutf8 = new ColumnFamily($this->client, 'SuperLongSubUTF8');
     $this->cf_valid_long = new ColumnFamily($this->client, 'ValidatorLong');
     $this->cf_valid_int = new ColumnFamily($this->client, 'ValidatorInt');
     $this->cf_valid_time = new ColumnFamily($this->client, 'ValidatorTime');
     $this->cf_valid_lex = new ColumnFamily($this->client, 'ValidatorLex');
     $this->cf_valid_ascii = new ColumnFamily($this->client, 'ValidatorAscii');
     $this->cf_valid_utf8 = new ColumnFamily($this->client, 'ValidatorUTF8');
     $this->cf_valid_bytes = new ColumnFamily($this->client, 'ValidatorBytes');
     $this->cf_def_valid = new ColumnFamily($this->client, 'DefaultValidator');
     $this->cfs = array($this->cf_long, $this->cf_int, $this->cf_ascii, $this->cf_time, $this->cf_lex, $this->cf_utf8, $this->cf_suplong, $this->cf_supint, $this->cf_suptime, $this->cf_suplex, $this->cf_supascii, $this->cf_suputf8, $this->cf_suplong_sublong, $this->cf_suplong_subint, $this->cf_suplong_subtime, $this->cf_suplong_sublex, $this->cf_suplong_subascii, $this->cf_suplong_subutf8, $this->cf_valid_long, $this->cf_valid_int, $this->cf_valid_time, $this->cf_valid_lex, $this->cf_valid_ascii, $this->cf_valid_utf8, $this->cf_valid_bytes, $this->cf_def_valid);
     $this->TIME1 = CassandraUtil::uuid1();
     $this->TIME2 = CassandraUtil::uuid1();
     $this->TIME3 = CassandraUtil::uuid1();
     $this->LEX1 = UUID::import('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')->bytes;
     $this->LEX2 = UUID::import('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')->bytes;
     $this->LEX3 = UUID::import('cccccccccccccccccccccccccccccccc')->bytes;
 }
Пример #9
0
 /**
  * Returns the static model of the specified AR class.
  * @param string $objectId The ID of the target object
  * @param string $objectType The type of the target object plus the underscore (_), for example, user_
  * @param string $className active record class name
  * @return User the static model class
  */
 public static function model($objectId, $objectType, $className = __CLASS__)
 {
     if (empty($objectId)) {
         $userId = Yii::app()->user->getId();
         if (!empty($userId)) {
             $objectId = CassandraUtil::import($userId)->__toString();
         } else {
             throw new InvalidArgumentException('Object ID is empty');
         }
     } else {
         $objectId = CassandraUtil::import($objectId)->__toString();
     }
     if (empty($objectType)) {
         $objectType = User::PREFIX;
     }
     // If there is an instance of this object, return it.
     if (isset(self::$_instances[$objectType . $objectId])) {
         return self::$_instances[$objectType . $objectId];
     } else {
         $newInstance = new Profile($objectId, $objectType);
         self::$_instances[$objectType . $objectId] = $newInstance;
         return $newInstance;
     }
 }
Пример #10
0
 function getUpcomingEventsForUser($user, $connection, $flag, $offset)
 {
     if (!$flag) {
         //		$query = "select se.socialeventid,se.title From SOCIALEVENT as se,PERSON_SOCIALEVENT as ps where se.socialeventid=ps.socialeventid and se.eventtimestamp>=CURRENT_TIMESTAMP and ps.username='******' ORDER BY se.eventdate ASC limit 3";
         $sql = new ColumnFamily($connection, 'PERSON_SOCIALEVENT');
         $index_exp_uname = CassandraUtil::create_index_expression('username', $user);
         $index_clause = CassandraUtil::create_index_clause(array($index_exp_uname), 0, 3);
         $rows = $sql->get_indexed_slices($index_clause, $columns = array('socialeventid'));
         $query = new ColumnFamily($connection, 'SOCIALEVENT');
         foreach ($rows as $key => $columns) {
             $index_exp1 = CassandraUtil::create_index_expression('socialeventid', $columns['socialeventid'], cassandra_IndexOperator::EQ);
             $index_exp2 = CassandraUtil::create_index_expression('eventtimestamp', time(), cassandra_IndexOperator::GTE);
             $index_clause1 = CassandraUtil::create_index_clause(array($index_exp1, $index_exp2));
             $queryresult = $query->get_indexed_slices($index_clause1);
             $queryresult = $query->get_indexed_slices($index_clause1);
             foreach ($queryresult as $key1 => $value1) {
                 $result[$key1] = $value1;
             }
         }
         $count = 1;
     } else {
         if ($flag) {
             //		$query = "select se.socialeventid,se.title From SOCIALEVENT as se,PERSON_SOCIALEVENT as ps where se.socialeventid=ps.socialeventid and se.eventtimestamp>=CURRENT_TIMESTAMP and ps.username='******' ORDER BY se.eventdate ASC limit $offset,10";
             $sql = new ColumnFamily($connection, 'PERSON_SOCIALEVENT');
             $index_exp_uname = CassandraUtil::create_index_expression('username', $user);
             $index_clause = CassandraUtil::create_index_clause(array($index_exp_uname), $offset, 10);
             $rows = $sql->get_indexed_slices($index_clause, $columns = array('socialeventid'));
             $query = new ColumnFamily($connection, 'SOCIALEVENT');
             foreach ($rows as $key => $columns) {
                 $index_exp1 = CassandraUtil::create_index_expression('socialeventid', $columns['socialeventid'], cassandra_IndexOperator::EQ);
                 $index_exp2 = CassandraUtil::create_index_expression('eventtimestamp', time(), cassandra_IndexOperator::GTE);
                 $index_clause1 = CassandraUtil::create_index_clause(array($index_exp1, $index_exp2));
                 $queryresult = $query->get_indexed_slices($index_clause1);
                 $queryresult = $query->get_indexed_slices($index_clause1);
                 foreach ($queryresult as $key1 => $value1) {
                     $result[$key1] = $value1;
                 }
             }
             $count = 1 + $offset;
         }
     }
     foreach ($result as $key1 => $row) {
         $rowsFound = true;
         $title = $row['title'];
         $se = $row['socialeventid'];
         $upcomingEvents = $upcomingEvents . " " . '<a href="events.php?socialEventID=' . $se . '">' . $count . '. ' . $title . '</a><br/>';
         $count++;
     }
     unset($result);
     return $upcomingEvents;
 }
Пример #11
0
 public function test_uuid1_generation()
 {
     $micros = 1293769171436849.0;
     $uuid = CassandraUtil::import(CassandraUtil::uuid1(null, $micros));
     $t = (int) ($uuid->time * 1000000);
     self::assertWithinMargin($micros, $t, 100);
 }
Пример #12
0
 public function recuperarTodosTimeline($de = '', $ate = '', array $filtros = null)
 {
     if ($de != '') {
         $de = CassandraUtil::import($de)->bytes;
     }
     if ($ate != '') {
         $ate = CassandraUtil::import($ate)->bytes;
     }
     $idFeeds = $this->_TimelineCF->get($filtros['usuario']->getId(), null, $de, $ate, true, $filtros['count']);
     $resultado = $this->_cf->multiget(array_keys($idFeeds));
     return $this->_criarVariosFromCassandra($resultado);
 }
Пример #13
0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * PHP Template.
 * Author: Sheetal Patil. Sun Microsystems, Inc.
 *
 */
session_start();
require_once "../etc/config.php";
require_once '../etc/phpcassa_config.php';
$friends = Users_Controller::getInstance();
$person = $_REQUEST['person'];
$friend = $_REQUEST['friend'];
$revokeSql = new ColumnFamily($conn, 'PERSON_PERSON');
$index_exp_person = CassandraUtil::create_index_expression('Person_username', $friend);
$index_exp_friend = CassandraUtil::create_index_expression('friends_username', $person);
$index_clause = CassandraUtil::create_index_clause(array($index_exp_person, $index_exp_friend));
$result = $revokeSql->get_indexed_slices($index_clause);
foreach ($result as $key => $col) {
    $revokeSql->remove($col['id']);
}
$outgoingRequests = $friends->outgoingRequests($person, $conn);
echo "<font color=green>You have revoked your friendship request to " . $friend . "</font>\n";
echo $outgoingRequests;
?>

Пример #14
0
 /**
  * @param WeLearn_DTO_IDTO $dto
  * @return boolean
  */
 protected function _adicionar(WeLearn_DTO_IDTO &$dto)
 {
     $dto->setId($dto->getModulo()->getId());
     $UUID = CassandraUtil::import($dto->getId());
     $this->_cf->insert($UUID->bytes, $dto->toCassandra());
     $dto->setPersistido(true);
 }
Пример #15
0
 /**
  * @param mixed $id
  * @return WeLearn_DTO_IDTO
  */
 public function remover($id)
 {
     $UUID = CassandraUtil::import($id);
     $recursoRemovido = $this->recuperar($id);
     $this->_cf->remove($UUID->bytes);
     if ($recursoRemovido instanceof WeLearn_Cursos_Recursos_RecursoRestrito) {
         $aulaUUID = CassandraUtil::import($recursoRemovido->getAula()->getId());
         $this->_recursosRestritosCF->remove($aulaUUID->bytes, array($UUID->bytes));
     } elseif ($recursoRemovido instanceof WeLearn_Cursos_Recursos_RecursoGeral) {
         $cursoUUID = CassandraUtil::import($recursoRemovido->getCurso()->getId());
         $this->_recursosGeraisCF->remove($cursoUUID->bytes, array($UUID->bytes));
     } else {
         throw new WeLearn_Base_Exception('A classe removida tem que derivar
                                          de WeLearn_Cursos_Recursos_Recurso.');
     }
     $recursoRemovido->setPersistido(false);
     return $recursoRemovido;
 }
Пример #16
0
 private function array_to_columns($array, $timestamp = null, $ttl = null)
 {
     if (empty($timestamp)) {
         $timestamp = CassandraUtil::get_time();
     }
     $ret = null;
     foreach ($array as $name => $value) {
         $column = new cassandra_Column();
         $column->name = $this->pack_name($name, false);
         $column->value = $this->pack_value($value, $name);
         $column->timestamp = $timestamp;
         $column->ttl = $ttl;
         $ret[] = $column;
     }
     return $ret;
 }
Пример #17
0
 protected static function mintTime($node = NULL, $time_arg = NULL)
 {
     /* Generates a Version 1 UUID.  
        These are derived from the time at which they were generated. */
     // Get time since Gregorian calendar reform in 100ns intervals
     // This is exceedingly difficult because of PHP's (and pack()'s)
     //  integer size limits.
     // Note that this will never be more accurate than to the microsecond.
     if ($time_arg == NULL) {
         $time = CassandraUtil::get_time() * 10 + self::interval;
     } else {
         $time = $time_arg * 10 + self::interval;
     }
     // Convert to a string representation
     $time = sprintf("%F", $time);
     preg_match("/^\\d+/", $time, $time);
     //strip decimal point
     // And now to a 64-bit binary representation
     $time = base_convert($time[0], 10, 16);
     $time = pack("H*", str_pad($time, 16, "0", STR_PAD_LEFT));
     // Reorder bytes to their proper locations in the UUID
     $uuid = $time[4] . $time[5] . $time[6] . $time[7] . $time[2] . $time[3] . $time[0] . $time[1];
     // Generate a random clock sequence
     $uuid .= self::randomBytes(2);
     // set variant
     $uuid[8] = chr(ord($uuid[8]) & self::clearVar | self::varRFC);
     // set version
     $uuid[6] = chr(ord($uuid[6]) & self::clearVer | self::version1);
     // Set the final 'node' parameter, a MAC address
     if ($node) {
         $node = self::makeBin($node, 6);
     }
     if (!$node) {
         // If no node was provided or if the node was invalid,
         //  generate a random MAC address and set the multicast bit
         $node = self::randomBytes(6);
         $node[0] = pack("C", ord($node[0]) | 1);
     }
     $uuid .= $node;
     return $uuid;
 }
 /**
  * Parses a slice row or {@see cassandra_ColumnOrSuperColumn} into a plain
  * array of data.
  *
  * @param cassandra_ColumnOrSuperColumn $row Row to parse
  * @return array Parsed plain array of data
  */
 protected function parseSliceRowX(cassandra_ColumnOrSuperColumn $row)
 {
     $result = array();
     if ($row->column !== null) {
         $nameType = $this->getColumnNameType();
         $valueType = $this->getColumnValueType($row->column->name);
         $name = CassandraUtil::unpack($row->column->name, $nameType);
         $value = CassandraUtil::unpack($row->column->value, $valueType);
         $result[$name] = $value;
     } else {
         if ($row->super_column !== null) {
             $superNameType = null;
             $superName = CassandraUtil::unpack($row->super_column->name, $superNameType);
             $values = array();
             foreach ($row->super_column->columns as $column) {
                 $nameType = $this->getColumnNameType();
                 $valueType = $this->getColumnValueType($column->name);
                 $name = CassandraUtil::unpack($column->name, $nameType);
                 $value = CassandraUtil::unpack($column->value, $valueType);
                 $values[$name] = $value;
             }
             $result[$superName] = $values;
         } else {
             // @codeCoverageIgnoreStart
             throw new Exception('Expected either normal or super column');
             // @codeCoverageIgnoreEnd
         }
     }
     return $result;
 }
Пример #19
0
 /**
  * Fetches a set of rows from this column family based on an index clause.
  *
  * @param string $indexColumn the name of the indexed column
  * @param mixed $indexValue the value of the column to retrieve
  * @param mixed[] $columns limit the columns or super columns fetched to this list
  * @param mixed $columnStart only fetch columns with name >= this
  * @param mixed $columnFinish only fetch columns with name <= this
  * @param bool $columnReversed fetch the columns in reverse order
  * @param int $columnCount limit the number of columns returned to this amount
  * @param mixed $superColumn return only columns in this super column
  * @param cassandra_ConsistencyLevel $readConsistencyLevel affects the guaranteed
  * 		 number of nodes that must respond before the operation returns
  *
  * @return mixed array(row_key => array(column_name => column_value))
  */
 public function getIndexedSlices($indexColumn, $indexValue, $columns = null, $columnStart = '', $columnFinish = '', $columnReversed = false, $columnCount = ColumnFamily::DEFAULT_COLUMN_COUNT, $superColumn = null, $readConsistencyLevel = null, $bufferSize = null)
 {
     if (empty($this->_columnFamily)) {
         $this->init();
     }
     $indexExp = CassandraUtil::create_index_expression($indexColumn, $indexValue);
     $indexClause = CassandraUtil::create_index_clause(array($indexExp));
     $row = $this->_columnFamily->get_indexed_slices($indexClause, $columns, $columnStart, $columnFinish, $columnReversed, $columnCount, $superColumn, $readConsistencyLevel, $bufferSize);
     foreach ($row as $key => $attributes) {
         $this->_rowKey = $key;
         $this->_attributes = $attributes;
         break;
     }
     if ($this->_rowKey === null) {
         return null;
     }
     return $this;
 }
Пример #20
0
 public function removerTodosPorAvaliacao(WeLearn_Cursos_Avaliacoes_Avaliacao $avaliacao)
 {
     try {
         $questoesRemovidas = $this->recuperarTodosPorAvaliacao($avaliacao);
     } catch (cassandra_NotFoundException $e) {
         return array();
     }
     foreach ($questoesRemovidas as $questao) {
         $questaoUUID = UUID::import($questao->getId());
         $alternativasRemovidas = $this->_alternativaDAO->removerTodosPorQuestao($questao);
         $this->_cf->remove($questaoUUID->bytes);
         $alternativaCorreta = null;
         for ($i = 0; $i < count($alternativasRemovidas); $i++) {
             if ($alternativasRemovidas[$i]->isCorreta()) {
                 $questao->setAlternativaCorreta($alternativasRemovidas[$i]);
                 unset($alternativasRemovidas[$i]);
                 break;
             }
         }
         $questao->setAlternativasIncorretas($alternativasRemovidas);
         $questao->setPersistido(false);
     }
     $avaliacaoUUID = CassandraUtil::import($avaliacao->getId());
     $this->_questaoPorAvaliacaoCF->remove($avaliacaoUUID->bytes);
     return $questoesRemovidas;
 }
Пример #21
0
 /**
  * @param WeLearn_DTO_IDTO $dto
  * @return boolean
  */
 protected function _adicionar(WeLearn_DTO_IDTO &$dto)
 {
     $UUID = UUID::mint();
     $dto->setId($UUID->string);
     $dto->setDataCriacao(time());
     $this->_cf->insert($UUID->bytes, $dto->toCassandra());
     $UUIDCurso = CassandraUtil::import($dto->getCurso()->getId());
     $this->_categoriasPorCursoCF->insert($UUIDCurso->bytes, array($UUID->bytes => ''));
     $dto->setPersistido(true);
 }
Пример #22
0
 /**
  * @param WeLearn_Usuarios_Usuario $usuario
  * @param WeLearn_Cursos_Enquetes_Enquete $enquete
  * @return bool
  */
 public function usuarioJaVotouEnquete(WeLearn_Usuarios_Usuario $usuario, WeLearn_Cursos_Enquetes_Enquete $enquete)
 {
     try {
         $enqueteUUID = CassandraUtil::import($enquete->getId());
         $this->_cf->get($enqueteUUID->bytes, array($usuario->getId()));
         return true;
     } catch (cassandra_NotFoundException $e) {
         return false;
     }
 }
             $operator = cassandra_IndexOperator::GT;
             break;
         case 'lte':
             $operator = cassandra_IndexOperator::LTE;
             break;
         case 'lt':
             $operator = cassandra_IndexOperator::LT;
             break;
         default:
             // Invalid operator
             break;
     }
     $arr_index_expression[] = CassandraUtil::create_index_expression($index_name, $column_value, $operator);
     $no_index_expression++;
 }
 $index_clause = CassandraUtil::create_index_clause($arr_index_expression, '', $nb_rows);
 $time_start = microtime(true);
 $result = $column_family->get_indexed_slices($index_clause);
 $time_end = microtime(true);
 $vw_row_vars['is_super_cf'] = $column_family->cfdef->column_type == 'Super';
 $vw_row_vars['is_counter_column'] = $column_family->cfdef->default_validation_class == 'org.apache.cassandra.db.marshal.CounterColumnType';
 $vw_vars['results_secondary_index'] = '';
 $vw_vars['results'] = '';
 $nb_results = 0;
 foreach ($result as $key => $value) {
     $vw_row_vars['key'] = $key;
     $vw_row_vars['value'] = $value;
     $vw_row_vars['keyspace_name'] = $keyspace_name;
     $vw_row_vars['columnfamily_name'] = $columnfamily_name;
     $vw_row_vars['show_actions_link'] = false;
     $vw_vars['results_secondary_index'] .= getHTML('columnfamily_browse_data_row.php', $vw_row_vars);
 function read_with_indexes($keyspace, $column_family, $indexes, $columns = null, $range = null, $consistency)
 {
     Loader::load("vendor", "phpcassa/columnfamily.php");
     $expressions = array();
     foreach ($indexes as $filter) {
         $expressions[] = CassandraUtil::create_index_expression($filter["column"], $filter["value"], !isset($filter["comparison"]) ? cassandra_IndexOperator::EQ : $filter["comparison"]);
     }
     $columnfamily = new columnfamily($this->connection($keyspace), $column_family, true, true, $consistency, $consistency, 500);
     if (isset($range) && is_array($range)) {
         if ($range["start"] != 0) {
             throw new Exception("Sorry, only ranges starting at 0 are currently supported");
         }
         $clause = CassandraUtil::create_index_clause($expressions, $range["start"], $range["length"]);
     } else {
         $clause = CassandraUtil::create_index_clause($expressions, "", 1000000);
     }
     //only the first million objects?
     $iterator = $columnfamily->get_indexed_slices($clause, $columns, "", "", false, 500, null, $consistency);
     $iterator->rewind();
     $data = array();
     while ($iterator->valid()) {
         $key = $iterator->key();
         $value = $iterator->current();
         $data[$key] = $value;
         $iterator->next();
     }
     return $data;
 }
Пример #25
0
 /**
  * @param WeLearn_DTO_IDTO $dto
  * @return boolean
  */
 protected function _atualizar(WeLearn_DTO_IDTO $dto)
 {
     $UUID = CassandraUtil::import($dto->getId());
     $cursoUUID = CassandraUtil::import($dto->getCurso()->getId());
     $dadosAntigos = $this->_cf->get($UUID->bytes, array('status', 'situacao'));
     $statusAntigo = (int) $dadosAntigos['status'];
     $situacaoAntiga = (int) $dadosAntigos['situacao'];
     $this->_cf->insert($UUID->bytes, $dto->toCassandra());
     if ($statusAntigo != $dto->getStatus()) {
         if ($dto->getStatus() == WeLearn_Cursos_Enquetes_StatusEnquete::ATIVA) {
             $this->_enquetePorStatusInativoCF->remove($cursoUUID->bytes, array($UUID->bytes));
             $this->_enquetePorStatusAtivoCF->insert($cursoUUID->bytes, array($UUID->bytes => ''));
         } else {
             $this->_enquetePorStatusAtivoCF->remove($cursoUUID->bytes, array($UUID->bytes));
             $this->_enquetePorStatusInativoCF->insert($cursoUUID->bytes, array($UUID->bytes => ''));
         }
     }
     if ($situacaoAntiga != $dto->getSituacao()) {
         if ($dto->getSituacao() == WeLearn_Cursos_Enquetes_SituacaoEnquete::ABERTA) {
             $this->_enquetePorSituacaoFechadoCF->remove($cursoUUID->bytes, array($UUID->bytes));
             $this->_enquetePorSituacaoAbertoCF->insert($cursoUUID->bytes, array($UUID->bytes => ''));
         } else {
             $this->_enquetePorSituacaoAbertoCF->remove($cursoUUID->bytes, array($UUID->bytes));
             $this->_enquetePorSituacaoFechadoCF->insert($cursoUUID->bytes, array($UUID->bytes => ''));
         }
     }
 }
Пример #26
0
 /**
  * @param mixed $id
  * @return WeLearn_DTO_IDTO
  */
 public function remover($id)
 {
     $UUID = CassandraUtil::import($id);
     $paginaRemovida = $this->recuperar($id);
     $aulaUUID = CassandraUtil::import($paginaRemovida->getAula()->getId());
     $this->_cf->remove($UUID->bytes);
     $this->_paginaPorAulaCF->remove($aulaUUID->bytes, array($paginaRemovida->getNroOrdem()));
     $curso = $paginaRemovida->getAula()->getModulo()->getCurso();
     $cursoUUID = CassandraUtil::import($curso->getId());
     $this->_contadorCF->add($this->_keyContador, $cursoUUID->bytes, -1);
     $controlePaginaDao = WeLearn_DAO_DAOFactory::create('ControlePaginaDAO', null, false);
     $idsAlunos = WeLearn_DAO_DAOFactory::create('AlunoDAO')->recuperarTodasIdsPorCurso($curso);
     for ($i = 0; $i < count($idsAlunos); $i++) {
         $cfKey = $idsAlunos[$i] . '::' . $curso->getId();
         $controlePaginaDao->decrementarPaginasVistas($cfKey);
     }
     $paginaRemovida->setPersistido(false);
     return $paginaRemovida;
 }
Пример #27
0
    $month = substr($eventdate, 5, 2);
    $day = substr($eventdate, 8, 2);
    $hour = substr($eventdate, 11, 2);
    $minute = substr($eventdate, 14, 2);
    $street1 = $row['street1'];
    $street2 = $row['street2'];
    $city = $row['city'];
    $state = $row['state'];
    $zip = $row['zip'];
    $country = $row['country'];
    unset($result);
    //    $q1="select tag from SOCIALEVENTTAG as st, SOCIALEVENTTAG_SOCIALEVENT as sst where sst.socialeventid='$se' and sst.socialeventtagid=st.socialeventtagid order by tag ASC";
    //    $result1 = $connection->query($q1);
    $sql = new ColumnFamily($conn, 'SOCIALEVENTTAG_SOCIALEVENT');
    $index_exp = CassandraUtil::create_index_expression('socialeventid', $se);
    $index_clause = CassandraUtil::create_index_clause(array($index_exp));
    $result1 = $sql->get_indexed_slices($index_clause, $columns = array('socialeventtagid'));
    $q1 = new ColumnFamily($conn, 'SOCIALEVENTTAG');
    foreach ($result1 as $key1 => $col1) {
        $row = $q1->get($col1['socialeventtagid']);
        $tg = $row['tag'];
        $tags = $tags . " " . $tg;
    }
    unset($result1);
}
if (!is_null($se) && (is_null($_SESSION["uname"]) || !($_SESSION["uname"] == $submitter))) {
    $fillMessage = "<font color=red>You can only edit events you created.</font> ";
} else {
    ob_start();
    require "../views/addEvent.php";
    $fillContent = ob_get_clean();
Пример #28
0
    }
} else {
    /*    $query = "select count(*) as count From SOCIALEVENT as se,PERSON_SOCIALEVENT as ps where se.socialeventid=ps.socialeventid and se.eventtimestamp>=CURRENT_TIMESTAMP and ps.username='******'";
        $result = $connection->query($query);
        $row = $result->getArray();
    */
    $row['count'] = 0;
    $sql = new ColumnFamily($conn, 'PERSON_SOCIALEVENT');
    $index_exp_uname = CassandraUtil::create_index_expression('username', $un);
    $index_clause = CassandraUtil::create_index_clause(array($index_exp_uname));
    $rows = $sql->get_indexed_slices($index_clause, $columns = array('socialeventid'));
    $query = new ColumnFamily($conn, 'SOCIALEVENT');
    foreach ($rows as $key => $columns) {
        $index_exp1 = CassandraUtil::create_index_expression('socialeventid', $columns['socialeventid'], cassandra_IndexOperator::EQ);
        $index_exp2 = CassandraUtil::create_index_expression('eventtimestamp', time(), cassandra_IndexOperator::GTE);
        $index_clause1 = CassandraUtil::create_index_clause(array($index_exp1, $index_exp2));
        $result = $query->get_indexed_slices($index_clause1);
        foreach ($result as $key1 => $value1) {
            $row['count'] += 1;
        }
    }
    $count = $row['count'];
    unset($result);
    $numPages = ceil($count / 10);
    $_SESSION["numPages"] = $numPages;
    $prev_page = 1;
    $next_page = 2;
    $curr_page = 1;
    $offset = 0;
    session_unregister("currentpage");
}
Пример #29
0
 /**
  * Processes the uploaded image.
  * @param CUploadedFile $uploadedImg The uploaded image
  * @param string $title The title (or caption) of this image (optional)
  * @param string $description The detailed description of this image (optional)
  * @param string $albumName The name of the album to put the image in (optional)
  * @return string The ID of new uploaded image | false
  */
 private function saveImg($uploadedImg, $title = '', $description = '', $albumName = '')
 {
     // Key
     $userId = CassandraUtil::import(Yii::app()->user->getId())->__toString();
     $key = $userId . '_' . CassandraUtil::uuid1();
     // Path
     $path = realpath(Yii::app()->params['storagePath']) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $userId;
     if (!is_dir($path)) {
         mkdir($path, 0775);
     }
     if (!empty($albumName)) {
         $path .= DIRECTORY_SEPARATOR . $albumName;
     }
     if (!is_dir($path)) {
         mkdir($path, 0775);
     }
     // Save the image information before processing the image
     $data = array('storage_path' => $uploadedImg->getTempName(), 'mime_type' => $uploadedImg->getType(), 'extension' => $uploadedImg->getExtensionName(), 'user_id' => Yii::app()->user->getId());
     if (!empty($title)) {
         $data['title'] = $title;
     }
     if (!empty($description)) {
         $data['description'] = $description;
     }
     if ($this->insert($key, $data) === false) {
         $uploadedImg->clean();
         return false;
     }
     // Render this image into different versions
     $photoTypes = Setting::model()->photo_types;
     // Get list of image types in JSON format. Decode it.
     $photoTypes = json_decode($photoTypes['value'], true);
     $img = Yii::app()->imagemod->load($data['storage_path']);
     $convertedImgs = array();
     foreach ($photoTypes as $type => $config) {
         $img->image_convert = 'jpg';
         $img->image_resize = true;
         $img->image_ratio = true;
         $img->image_x = $config['width'];
         $img->image_y = $config['height'];
         if (isset($config['suffix'])) {
             $img->file_safe_name = $key . $config['suffix'] . '.jpg';
         } else {
             $img->file_safe_name = $key . '.jpg';
         }
         $img->process($path);
         if (!$img->processed) {
             // Delete the original image
             $uploadedImg->clean();
             // Delete the record in db
             $this->delete($key);
             // Log the error
             Yii::log('Cannot resize the image ' . $data['storage_path'] . ' to ' . $path . '/' . $img->file_safe_name, 'error', 'application.modules.storage.Storage');
             // Delete all converted images
             foreach ($convertedImgs as $imgType => $imgPath) {
                 unlink($imgPath);
             }
             // Return false
             return false;
         } else {
             // Remember the path of converted image
             $convertedImgs[$type] = $img->file_dst_path;
         }
         // Update the database
         $data = array('storage_path' => $convertedImgs['original'], 'mime_type' => 'image/jpeg', 'extension' => 'jpg');
         unset($convertedImgs['original']);
         $data = array_merge($data, $convertedImgs);
         if ($this->insert($key, $data) === false) {
             // Delete the original image
             $uploadedImg->clean();
             // Delete the record in db
             $this->delete($key);
             // Log the error
             Yii::log('Cannot resize the image ' . $data['storage_path'] . ' to ' . $path . '/' . $img->file_safe_name, 'error', 'application.modules.storage.Storage');
             // Delete all converted images
             unlink($data['storage_path']);
             foreach ($convertedImgs as $imgType => $imgPath) {
                 unlink($imgPath);
             }
             // Return false
             return false;
         }
     }
     // Delete the temporary image
     $uploadedImg->clean();
     return $key;
 }
Пример #30
0
 public function array_to_columns($array, $timestamp = null)
 {
     if (empty($timestamp)) {
         $timestamp = CassandraUtil::get_time();
     }
     $ret = null;
     foreach ($array as $name => $value) {
         $column = new cassandra_Column();
         $column->name = $this->unparse_column_name($name, false);
         $column->value = $this->to_column_value($value);
         $column->timestamp = $timestamp;
         $ret[] = $column;
     }
     return $ret;
 }