public function diffDias($data) { $date = new \Datetime(null); $hoje = $date->getTimestamp() + $date->getOffset(); $diff = strtotime($data) - $hoje; return floor($diff / (24 * 60 * 60)); }
public function getParams() { $params = ['get_sent_offers' => $this->getSentOffers, 'get_received_offers' => $this->getReceivedOffers, 'get_descriptions' => $this->getDescriptions, 'active_only' => $this->activeOnly, 'historical_only' => $this->historicalOnly]; empty($this->language) ?: ($params['language'] = $this->language); empty($this->timeHistoricalCutoff) ?: ($params['time_historical_cutoff'] = $this->timeHistoricalCutoff->getTimestamp()); return $params; }
public function actionExportar() { // get your HTML raw content without any layouts or scripts if (isset($_COOKIE['pcbuilder_cart'])) { $total = 0; $pcbuilder_cart = unserialize($_COOKIE['pcbuilder_cart']); if (count($pcbuilder_cart) > 0) { $pcbuilder_cart = Yii::$app->PCBuilder->array_sort($pcbuilder_cart, 'categoria', 'SORT_ASC'); foreach ($pcbuilder_cart as $i => $peca) { $modelPeca = Pecas::findOne($peca['peca']); $pecas[] = ['id' => $modelPeca['id'], 'cookieID' => $i, 'nome' => $modelPeca['nome'], 'loja' => $modelPeca['loja'], 'link_externo' => $modelPeca['link_externo'], 'preco' => $modelPeca['preco'][0]['preco']]; $total = $total + $modelPeca['preco'][0]['preco']; } } } else { echo "Nada para salvar!"; exit; } if (count($pecas) > 0) { $content = $this->renderPartial('_pdf', ['pecas' => $pecas, 'total' => $total]); $date = new \Datetime(null); $hoje = $date->getTimestamp() + $date->getOffset(); // setup kartik\mpdf\Pdf component $pdf = new Pdf(['mode' => Pdf::MODE_BLANK, 'format' => Pdf::FORMAT_A4, 'orientation' => Pdf::ORIENT_PORTRAIT, 'destination' => Pdf::DEST_DOWNLOAD, 'content' => $content, 'filename' => 'PC Builder - Lista de Peças - ' . date("d.m.Y H.i.s", $hoje) . '.pdf', 'options' => ['title' => 'PC Builder - Lista de Peças - ' . date("d/m/Y H:i:s", $hoje), 'defaultheaderline' => 0, 'setAutoTopMargin' => 'stretch'], 'methods' => ['SetHeader' => ['' . '<table width="100%">' . '<tr>' . '<td width="75%"><a target="_blank" href="http://www.brunodeoliveira.com"><img width="100px" src="imgs/logo.png"></a></td>' . '<td width="25%" valign="bottom" style="text-align: right">Salvo em<br /><small>' . date("d/m/Y H:i:s") . '</small></td>' . '<tr/>' . '</table>' . ''], 'SetFooter' => ['Obrigado por utilizar o PC Builder - Desenvolvido por Bruno de Oliveira - Página {PAGENO}']]]); return $pdf->render(); } }
private function sync_orders($woo_id, $url, $start_at, $batch_size = 100) { echo "Syncing with {$url}.\n"; $mongo_orders = $this->mongo_db->selectCollection('orders'); $t = new DateTime("@{$start_at}"); $start_at_t = $t->format(DateTime::RFC3339); $start_at_t = mb_substr($start_at_t, 0, mb_strlen($start_at_t) - 6) . 'Z'; $pages = $at_page = 1; while ($at_page <= $pages) { $result = $this->wcc->orders->get(null, array('filter[updated_at_min]' => $start_at_t, 'filter[limit]' => $batch_size, 'filter[offset]' => $at_page * $batch_size)); if (isset($result['http']['response']['headers']['X-WC-TotalPages'])) { $pages = (int) $result['http']['response']['headers']['X-WC-TotalPages']; } if (isset($result['orders'])) { foreach ($result['orders'] as $order) { $created_at = new DateTime($order['created_at']); $updated_at = new Datetime($order['updated_at']); $completed_at = new DateTime($order['completed_at']); $order['shoplab_user_id'] = $woo_id; $order['created_at_ts'] = $created_at->getTimestamp(); $order['updated_at_ts'] = $updated_at->getTimestamp(); $order['completed_at_ts'] = $completed_at->getTimestamp(); $mongo_orders->update(array('shoplab_user_id' => $order['shoplab_user_id'], 'order_number' => $order['order_number']), $order, array('upsert' => true)); } } if (0 < $pages) { echo "Fetched page {$at_page} (batch size {$batch_size}) of {$pages}.\n"; } else { echo "Nothing more to fetch.\n"; } $at_page++; } }
/** * Save or update a visitor. */ public function registerVisistor($ipAdress, $pageName) { $isAdmin = $this->securityContext->isGranted(Constants::ROLE_ADMIN); if ($isAdmin) { $dateNow = new \Datetime(); $currentPage = $this->getPageByName($pageName); $totalVisitsPage = $this->getPageByName(Constants::TOTAL_PAGE_NAME); // On cherche le visiteur dans la BDD via son adresse $visitor = $this->findVisitorByIpAddress($ipAdress); if ($visitor !== null) { // Si le visiteur est d�j� connu et sa derni�re connection date de plus // de 5 minutes on consid�re que c'est une nouvelle visite $seconds = $dateNow->getTimestamp() - $visitor->getLastConnection()->getTimestamp(); if ($seconds > 5 * 60) { // new visit $totalVisitsPage->incrementVisits(); $currentPage->incrementVisits(); } // On met simplement � jour sa date de derni�re connection $visitor->setLastConnection($dateNow); } else { // nouveau visiteur $totalVisitsPage->incrementVisits(); $currentPage->incrementVisits(); // On enregistre le visiteur $visitor = $this->createVisitor($ipAdress); } if (!$visitor->hasAlreadyVisitedPage($currentPage)) { $visitor->addPage($currentPage); } } // save or update all entities $this->em->flush(); return $this; }
/** * Normalizes DateTime object * * @param null|\Datetime $utcDatetime * * @return null|string */ protected function normalizeDateTime($utcDatetime) { if (!$utcDatetime instanceof \DateTime) { return; } $datetime = new \DateTime(); $datetime->setTimestamp($utcDatetime->getTimestamp()); return $datetime->format('Y-m-d g:i:s A'); }
/** * @return bool */ public function isPublished() { $isStatusPublished = parent::isPublished(); $currentTimestamp = time(); if ($isStatusPublished && (null !== $this->publicationDate && $currentTimestamp >= $this->publicationDate->getTimestamp())) { return true; } return false; }
/** * formatDate * Format a datetime to a readable date according to the locale * @param \Datetime $date */ public function formatDate(\Datetime $date) { $locale = $this->container->getParameter('locale'); $format = "%A, %#d %B %Y"; // windows does not support %e so we put %#d if (substr($locale, 0, 2) === "fr") { $format = str_replace(',', '', $format); } return strftime($format, $date->getTimestamp()); }
/** * @covers WindowsAzure\MediaServices\Models\TaskHistoricalEvent::getTimeStamp * @covers WindowsAzure\MediaServices\Models\TaskHistoricalEvent::__construct */ public function testGetTimeStamp() { // Setup $options = array('TimeStamp' => '2013-11-27'); $time = new \Datetime($options['TimeStamp']); $histEvent = TaskHistoricalEvent::createFromOptions($options); // Test $result = $histEvent->getTimeStamp(); // Assert $this->assertEquals($time->getTimestamp(), $result->getTimestamp()); }
public function __construct() { $this->dateDeb = new \Datetime(); //$this->dateFin = new \Datetime(); $dateBase = new \Datetime(); $duration = 3600 * 24 * 3; $endtimestamp = $dateBase->getTimestamp() + $duration; $dateBase->setTimestamp($endtimestamp); $this->dateFin = $dateBase; $this->voteA = 0; $this->voteB = 0; }
public function actionEventos($from, $to) { $date = new \Datetime(null); $hoje = $date->getTimestamp() + $date->getOffset(); $de = date("Y-m-d", $from / 1000); $para = date("Y-m-d", $to / 1000); $model = Eventos::find()->joinWith('atividade')->where(['>=', 'd_ini', $de])->orWhere(['<=', 'd_ter', $de])->orWhere(['<=', 'd_ter', $para])->andWhere(['atividades.empresa_id' => Yii::$app->session->get('empresa')])->all(); $d = ['success' => 1]; foreach ($model as $dados) { $d['result'][] = ['id' => $dados['id'], 'title' => $dados['atividade']['atividade'], 'url' => Url::to(['evento/visualizar', 'id' => $dados['id']]), 'class' => Yii::$app->AgobUtils->cssStatus($dados['status'], $dados['d_ter']), 'start' => strtotime($dados['d_ini']) . '000', 'end' => strtotime($dados['d_ter']) . '000', 'dias' => Yii::$app->AgobUtils->diffDias($dados['d_ter']), 'status' => $dados['status']]; } echo json_encode($d); }
public function searchDateAction() { $form = $this->_getDateSearchForm(); if ($form->isValid() && ($data = $form->getFilteredData())) { try { $from = new \Datetime($data['from']); $to = new \Datetime($data['to']); } catch (\Exception $e) { $this->addFlash('error', 'Invalid input for dates!'); return $this->redirectToReferer(); } return $this->redirectToRoute('ms.cp.discount.listing.active.date', array('fromTimestamp' => $from->getTimestamp(), 'toTimestamp' => $to->getTimestamp())); } }
public function historiqueAction() { $source = null; $cible = null; $request = $this->getRequest(); $montant = ""; $repository = $this->getDoctrine()->getManager()->getRepository('ConvertDeviseBundle:Devise'); $devise = $repository->findAll(); // On vérifie qu'elle est de type POST if ($request->getMethod() == 'POST') { $source = $request->request->get('_source'); $cible = $request->request->get('_cible'); $montant = $request->request->get('_montant'); $sourcecible = $source . $cible; $this->getparamAction(); //connexion entre api yahoo et application $this->convertAction($sourcecible); $t = new \Datetime(); $t->getTimestamp(); $datedemande = $t; $etatip = 1; //adresse ip du client $ipdclient = $_SERVER["REMOTE_ADDR"]; $this->getclientAction($ipdclient, $datedemande); $cour = $this->cour; $nbdemande = 1; $hist = new Historique(); $hist->setSource($source); $hist->setCible($cible); $hist->setDatedemande($datedemande); $hist->setNbdemande($nbdemande); $hist->setCour($cour); $hist->setMontant($montant); $hist->setIpdclient($ipdclient); if ($this->bloque == true) { $etatip = 0; $hist->setEtatip($etatip); $em = $this->getDoctrine()->getManager(); $em->persist($hist); $em->flush(); return $this->render('ConvertDeviseBundle:Devise:blacklist.html.twig'); } else { $hist->setEtatip($etatip); $em = $this->getDoctrine()->getManager(); $em->persist($hist); $em->flush(); } } return $this->render('ConvertDeviseBundle:Devise:index.html.twig', array('devise' => $devise, 'cour' => $this->cour, 'montant' => $montant, 'source' => $source, 'cible' => $cible)); }
public function getTimeAgo(\Datetime $date) { $time = time() - $date->getTimestamp(); $units = array(31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second'); $aMap = array("year" => "a", "month" => "a", "week" => "a", "day" => "a", "hour" => "an", "minute" => "a", "second" => "a"); foreach ($units as $unit => $label) { if ($time < $unit) { continue; } $numberOfUnits = floor($time / $unit); $a = $aMap[$label]; return $label == 'second' ? 'a few seconds ago' : ($numberOfUnits > 1 ? $numberOfUnits : $a) . ' ' . $label . ($numberOfUnits > 1 ? 's' : '') . ' ago'; } }
public function createAction(request $request, $username) { $em = $this->getDoctrine()->getManager(); //we get the host and the invited user $host = $this->container->get('security.context')->getToken()->getUser(); $guest = $em->getRepository('BFUserBundle:User')->findOneByUsername($username); //we check that the host and guest are not the same person if ($host == $guest) { throw new NotFoundHttpException("You can't create a duel against yourself."); } //we create a new duel and set the users to the duel $date = new \Datetime(); $duration = 7 * 24 * 60 * 60; $endtimestamp = $date->getTimestamp() + $duration; $date->setTimestamp($endtimestamp); $duel = new Duel(); $duel->setBeginDate(new \Datetime())->setEndDate($date)->setAccepted('0')->setCompleted('0')->setHostCompleted('0')->setGuestCompleted('0')->setHost($host)->setGuest($guest)->setType('duel')->addUser($host)->addUser($guest); //getting the code for the duel $service = $this->container->get('bf_site.randomcode'); $code = $service->generate('duel'); $duel->setCode($code); $message = 'You received an invitation for a duel from ' . $host->getUsername(); $link = $this->generateUrl('bf_site_profile_duels'); //we create a notification for the guest. $service = $this->container->get('bf_site.notification'); $notification = $service->create($guest, $message, $duel, $link); $request = $this->get('request'); if ($request->getLocale() == 'en') { $form = $this->get('form.factory')->create(new DuelType(), $duel); } elseif ($request->getLocale() == 'fr') { $form = $this->get('form.factory')->create(new DuelFRType(), $duel); } if ($form->handleRequest($request)->isValid()) { //we check if the user wants to receive a mail. If so, we send him an email. $em = $this->getDoctrine()->getManager(); $em->persist($notification); $em->persist($duel); $em->flush(); if ($guest->getMailDuel() === true) { $message = \Swift_Message::newInstance()->setSubject($host->getUsername() . ' invited you for a duel on bestfootball')->setFrom('*****@*****.**')->setTo($guest->getEmail())->setBody($this->renderView('Emails/duel.html.twig', array('host' => $host, 'guest' => $guest, 'duel' => $duel)), 'text/html'); $this->get('mailer')->send($message); } $this->addFlash('success', 'Your invitation for a duel has been send to ' . $guest->getUsername() . ' you will have to wait for ' . $guest->getUsername() . ' to accept it.'); return $this->redirect($this->generateUrl('bf_site_profile', array('username' => $guest->getUsername()))); } return $this->render('BFSiteBundle:Duel:create.html.twig', array('form' => $form->createView())); }
/** * @covers WindowsAzure\MediaServices\Models\JobTemplate::createFromOptions * @covers WindowsAzure\MediaServices\Models\JobTemplate::fromArray */ public function testCreateFromOptions() { // Setup $jobTemplateBody = 'JobTemplateBody'; $templateType = JobTemplate::TYPE_ACCOUNT_LEVEL; $options = array('Id' => 'sfgsfg34', 'Name' => 'Some Name', 'Created' => '2013-11-25', 'LastModified' => '2013-11-25', 'JobTemplateBody' => 'Some Body Of Job Template', 'NumberofInputAssets' => 6, 'TemplateType' => JobTemplate::TYPE_SYSTEM_LEVEL); $created = new \Datetime($options['Created']); $modified = new \Datetime($options['LastModified']); // Test $jobTempl = JobTemplate::createFromOptions($options); // Assert $this->assertEquals($options['Id'], $jobTempl->getId()); $this->assertEquals($options['Name'], $jobTempl->getName()); $this->assertEquals($created->getTimestamp(), $jobTempl->getCreated()->getTimestamp()); $this->assertEquals($modified->getTimestamp(), $jobTempl->getLastModified()->getTimestamp()); $this->assertEquals($options['JobTemplateBody'], $jobTempl->getJobTemplateBody()); $this->assertEquals($options['NumberofInputAssets'], $jobTempl->getNumberOfInputAssets()); $this->assertEquals($options['TemplateType'], $jobTempl->getTemplateType()); }
public function compute($checkbox, $weight, $userDate) { if (!$checkbox || $userDate == null) { return; } $userDate = new \Datetime($userDate); $max = 0; // compute distance foreach ($this->metastores as &$metastore) { $videoDate = new \Datetime($metastore->publishedAt); $distance = abs($userDate->getTimestamp() - $videoDate->getTimestamp()); $metastore->dateDistance = $distance; if ($distance > $max) { $max = $distance; } } // normalize foreach ($this->metastores as &$metastore) { $metastore->dateDistanceNormalized = (1 - $metastore->dateDistance / $max) * $weight; } }
/** * Creates a new JobModel model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new JobModel(); $now = new \DateTime(); $now = $now->getTimestamp(); // var_dump($now); // var_dump(Yii::$app->user->identity); // die; $model->modify_time = $model->create_time = $now; $model->modify_user = $model->create_user = $model->owner = Yii::$app->user->identity->username; $model->cron_str = "1 * * * *"; #$date = date_create(); # php, hehe $date = date('Y-m-d'); $date = new \Datetime($date); // $date = $date->getTimestamp(); $model->start_date = $date->getTimestamp(); $model->end_date = $date->add(new \DateInterval('P99Y')); $model->host_strategy = 0; $model->restore_strategy = 0; $model->retry_strategy = 0; $model->error_strategy = 0; $model->exist_strategy = 0; $model->mails = Yii::$app->user->identity->mail; $model->next_run_time = 0; $model->status = 0; $model->running_timeout_s = 99999; $model->oupput_match_reg = 'error'; $model->team = 'backend'; $model->phones = '10086'; $model->desc = ' '; // $model->phone = Yii::$app->user->identity->phone; if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', ['model' => $model]); } }
/** * Overwrite save to set the uri if it's not already set and recalculate the minutes. */ public function save() { // Prevent http://jira.opensource.mayflower.de/jira/browse/PHPROJEKT-450 if (is_null($this->notes)) { $this->notes = ''; } if (empty($this->endTime)) { $this->minutes = null; } else { $start = new Datetime($this->startDatetime); $end = new Datetime(substr($this->startDatetime, 0, 11) . $this->endTime); $this->minutes = floor(($end->getTimestamp() - $start->getTimestamp()) / 60); } if (empty($this->uid)) { $this->uid = Phprojekt::generateUniqueIdentifier(); } if (empty($this->uri)) { $this->uri = $this->uid; } if (!$this->projectId) { $this->projectId = 1; } return parent::save(); }
/** * @covers WindowsAzure\MediaServices\Models\TaskTemplate::getLastModified */ public function testGetLastModified() { // Setup $options = array('NumberofInputAssets' => 4, 'NumberofOutputAssets' => 3, 'LastModified' => '2013-11-27'); $task = TaskTemplate::createFromOptions($options); $modified = new \Datetime($options['LastModified']); // Test $result = $task->getLastModified(); // Assert $this->assertEquals($modified->getTimestamp(), $result->getTimestamp()); }
public function __tostring() { return $this->user->__tostring() . ' (' . date('d/m/Y à H:i:s', $this->created->getTimestamp()) . ')'; }
/** * set imported in bulk query * * @param $ids */ protected function _setImported($ids) { try { $coreResource = $this->_resource; $write = $coreResource->getConnection('core_write'); $tableName = $coreResource->getTableName('email_review'); $ids = implode(', ', $ids); $now = new \Datetime(); $nowDate = $this->_dateTime->formatDate($now->getTimestamp()); $write->update($tableName, array('review_imported' => 1, 'updated_at' => $nowDate), "review_id IN ({$ids})"); } catch (\Exception $e) { $this->_helper->debug((string) $e, array()); } }
/** * @covers WindowsAzure\MediaServices\Models\Job::getStartTime */ public function testGetStartTime() { // Setup $options = array('StartTime' => '2013-11-25'); $startTime = new \Datetime($options['StartTime']); $job = Job::createFromOptions($options); // Test $result = $job->getStartTime(); // Assert $this->assertEquals($startTime->getTimestamp(), $result->getTimestamp()); }
/** * @covers WindowsAzure\MediaServices\Models\AssetFile::createFromOptions * @covers WindowsAzure\MediaServices\Models\AssetFile::fromArray */ public function testAssetFileFromOptions() { // Setup $assetFileArray = array('Id' => 'dfhdgh56', 'Name' => 'newAssetFile', 'ContentFileSize' => '20 mb', 'ParentAssetId' => 'kdjfg67', 'EncryptionVersion' => 'EncryptionVersion', 'EncryptionScheme' => 'EnryptionScheme', 'IsEncrypted' => true, 'EncryptionKeyId' => 'keyId896', 'InitializationVector' => 'InitVector', 'IsPrimary' => true, 'LastModified' => '2013-11-19', 'Created' => '2013-11-19', 'MimeType' => 'type of mime', 'ContentChecksum' => 'ContentChecksum'); $created = new \Datetime($assetFileArray['Created']); $modified = new \Datetime($assetFileArray['LastModified']); // Test $resultAssetFile = AssetFile::createFromOptions($assetFileArray); // Assert $this->assertEquals($assetFileArray['Id'], $resultAssetFile->getId()); $this->assertEquals($assetFileArray['Name'], $resultAssetFile->getName()); $this->assertEquals($assetFileArray['ContentFileSize'], $resultAssetFile->getContentFileSize()); $this->assertEquals($assetFileArray['ParentAssetId'], $resultAssetFile->getParentAssetId()); $this->assertEquals($assetFileArray['EncryptionVersion'], $resultAssetFile->getEncryptionVersion()); $this->assertEquals($assetFileArray['EncryptionScheme'], $resultAssetFile->getEncryptionScheme()); $this->assertEquals($assetFileArray['IsEncrypted'], $resultAssetFile->getIsEncrypted()); $this->assertEquals($assetFileArray['EncryptionKeyId'], $resultAssetFile->getEncryptionKeyId()); $this->assertEquals($assetFileArray['InitializationVector'], $resultAssetFile->getInitializationVector()); $this->assertEquals($assetFileArray['IsPrimary'], $resultAssetFile->getIsPrimary()); $this->assertEquals($modified->getTimestamp(), $resultAssetFile->getLastModified()->getTimestamp()); $this->assertEquals($created->getTimestamp(), $resultAssetFile->getCreated()->getTimestamp()); $this->assertEquals($assetFileArray['MimeType'], $resultAssetFile->getMimeType()); $this->assertEquals($assetFileArray['ContentChecksum'], $resultAssetFile->getContentCheckSum()); }
/** * @param Configuration $configuration * @param User $owner * @param bool $isValidated * * @throws InvalidConfigurationException * @return SimpleWorkbolspace * * The template doesn't need to be validated anymore if * - it comes from the self::import() function * - we want to create a user from the default template (it should work no matter what) */ public function createWorkspace(Configuration $configuration, User $owner, $isValidated = false) { $configuration->setOwner($owner); $data = $configuration->getData(); $this->data = $data; $this->om->startFlushSuite(); $this->setImporters($configuration, $data); if (!$isValidated) { $this->validate($data, false); $isValidated = true; } $workspace = new Workspace(); $workspace->setName($configuration->getWorkspaceName()); $workspace->setCode($configuration->getWorkspaceCode()); $workspace->setDescription($configuration->getWorkspaceDescription()); $workspace->setGuid($this->container->get('claroline.utilities.misc')->generateGuid()); $workspace->setDisplayable($configuration->isDisplayable()); $workspace->setSelfRegistration($configuration->getSelfRegistration()); $workspace->setRegistrationValidation($configuration->getRegistrationValidation()); $workspace->setSelfUnregistration($configuration->getSelfUnregistration()); $date = new \Datetime(date('d-m-Y H:i')); $workspace->setCreationDate($date->getTimestamp()); $this->om->persist($workspace); $this->om->flush(); $this->log('Base workspace created...'); //load roles $this->log('Importing roles...'); $entityRoles = $this->getImporterByName('roles')->import($data['roles'], $workspace); //The manager role is required for every workspace $entityRoles['ROLE_WS_MANAGER'] = $this->container->get('claroline.manager.role_manager')->createWorkspaceRole("ROLE_WS_MANAGER_{$workspace->getGuid()}", 'manager', $workspace, true); $defaultZip = $this->container->getParameter('claroline.param.templates_directory') . 'default.zip'; //batch import with default template shouldn't be flushed if ($configuration->getArchive() !== $defaultZip) { $this->om->forceFlush(); } $this->log('Roles imported...'); $owner->addRole($entityRoles['ROLE_WS_MANAGER']); $this->om->persist($owner); //add base roles to the role array $pfRoles = $this->om->getRepository('ClarolineCoreBundle:Role')->findAllPlatformRoles(); foreach ($pfRoles as $pfRole) { $entityRoles[$pfRole->getName()] = $pfRole; } $entityRoles['ROLE_ANONYMOUS'] = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneByName('ROLE_ANONYMOUS'); $entityRoles['ROLE_USER'] = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneByName('ROLE_USER'); $dir = new Directory(); $dir->setName($workspace->getName()); $dir->setIsUploadDestination(true); $root = $this->container->get('claroline.manager.resource_manager')->create($dir, $this->om->getRepository('Claroline\\CoreBundle\\Entity\\Resource\\ResourceType')->findOneByName('directory'), $owner, $workspace, null, null, array()); $this->log('Populating the workspace...'); $this->populateWorkspace($workspace, $configuration, $root, $entityRoles, true, false); $this->container->get('claroline.manager.workspace_manager')->createWorkspace($workspace); if ($owner) { $this->log('Set the owner...'); $workspace->setCreator($owner); } $this->om->endFlushSuite(); $fs = new FileSystem(); return $workspace; }
/** * @param File $template * @param User $owner * @param bool $isValidated * * @throws InvalidConfigurationException * * @return SimpleWorkbolspace * * The template doesn't need to be validated anymore if * - it comes from the self::import() function * - we want to create a user from the default template (it should work no matter what) */ public function createWorkspace(Workspace $workspace, File $template, $isValidated = false) { $data = $this->container->get('claroline.manager.workspace_manager')->getTemplateData($template, true); if ($workspace->getCode() === null) { $workspace->setCode($data['parameters']['code']); } if ($workspace->getName() === null) { $workspace->setName($data['parameters']['name']); } //just to be sure doctrine is ok before doing all the workspace $this->om->startFlushSuite(); $this->setImporters($template, $workspace->getCreator()); if (!$isValidated) { $this->validate($data, false); $isValidated = true; } $workspace->setGuid($this->container->get('claroline.utilities.misc')->generateGuid()); $date = new \Datetime(date('d-m-Y H:i')); $workspace->setCreationDate($date->getTimestamp()); $this->om->persist($workspace); $this->om->flush(); $this->log("Base {$workspace->getCode()} workspace created..."); //load roles $this->log('Importing roles...'); $entityRoles = $this->getImporterByName('roles')->import($data['roles'], $workspace); //The manager role is required for every workspace $entityRoles['ROLE_WS_MANAGER'] = $this->container->get('claroline.manager.role_manager')->createWorkspaceRole("ROLE_WS_MANAGER_{$workspace->getGuid()}", 'manager', $workspace, true); //batch import with default template shouldn't be flushed if (strpos($template->getPathname(), 'default.zip') === false && strpos($template->getPathname(), 'personal.zip') === false) { $this->om->forceFlush(); } $owner = $workspace->getCreator(); $this->log('Roles imported...'); $owner->addRole($entityRoles['ROLE_WS_MANAGER']); $this->om->persist($owner); //add base roles to the role array $pfRoles = $this->om->getRepository('ClarolineCoreBundle:Role')->findAllPlatformRoles(); foreach ($pfRoles as $pfRole) { $entityRoles[$pfRole->getName()] = $pfRole; } $entityRoles['ROLE_ANONYMOUS'] = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneByName('ROLE_ANONYMOUS'); $entityRoles['ROLE_USER'] = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneByName('ROLE_USER'); $dir = new Directory(); $dir->setName($workspace->getName()); $dir->setIsUploadDestination(true); $root = $this->container->get('claroline.manager.resource_manager')->create($dir, $this->om->getRepository('Claroline\\CoreBundle\\Entity\\Resource\\ResourceType')->findOneByName('directory'), $owner, $workspace, null, null, []); $this->log('Populating the workspace...'); $this->populateWorkspace($workspace, $template, $root, $entityRoles, true, false); $this->container->get('claroline.manager.workspace_manager')->createWorkspace($workspace); $this->om->endFlushSuite(); return $workspace; }
/** * Import a workspace list from a csv data. * * @param array $workspaces */ public function importWorkspaces(array $workspaces, $logger = null) { $this->om->clear(); $ds = DIRECTORY_SEPARATOR; $i = 0; $j = 0; $workspaceModelManager = $this->container->get('claroline.manager.workspace_model_manager'); foreach ($workspaces as $workspace) { $this->om->startFlushSuite(); $model = null; $name = $workspace[0]; $code = $workspace[1]; $isVisible = $workspace[2]; $selfRegistration = $workspace[3]; $registrationValidation = $workspace[4]; $selfUnregistration = $workspace[5]; if (isset($workspace[6])) { $user = $this->om->getRepository('ClarolineCoreBundle:User')->findOneByUsername($workspace[6]); } else { $user = $this->container->get('security.context')->getToken()->getUser(); } if (isset($workspace[7])) { $model = $this->om->getRepository('ClarolineCoreBundle:Model\\WorkspaceModel')->findOneByName($workspace[7]); } if ($model) { $guid = $this->ut->generateGuid(); $workspace = new Workspace(); $this->createWorkspace($workspace); $workspace->setName($name); $workspace->setCode($code); $workspace->setDisplayable($isVisible); $workspace->setSelfRegistration($selfRegistration); $workspace->setSelfUnregistration($selfUnregistration); $workspace->setRegistrationValidation($registrationValidation); $workspace->setGuid($guid); $date = new \Datetime(date('d-m-Y H:i')); $workspace->setCreationDate($date->getTimestamp()); $workspace->setCreator($user); $workspaceModelManager->addDataFromModel($model, $workspace, $user, $errors); } else { //this should be changed later $configuration = new Configuration($this->templateDir . $ds . 'default.zip'); $configuration->setWorkspaceName($name); $configuration->setWorkspaceCode($code); $configuration->setDisplayable($isVisible); $configuration->setSelfRegistration($selfRegistration); $configuration->setSelfUnregistration($registrationValidation); $this->container->get('claroline.manager.transfert_manager')->createWorkspace($configuration, $user); } $i++; $j++; if ($i % self::MAX_WORKSPACE_BATCH_SIZE === 0) { if ($logger) { $logger(" [UOW size: " . $this->om->getUnitOfWork()->size() . "]"); } $i = 0; $this->om->forceFlush(); if ($logger) { $logger(" Workspace {$j} ({$name}) being created"); } $this->om->clear(); } $this->om->endFlushSuite(); } }
/** * Set datetime * * @param \Datetime $time * @return History */ public function setDatetime(\Datetime $time) { $this->datetime = $time->getTimestamp(); return $this; }
/** * @covers WindowsAzure\MediaServices\Models\IngestManifestAsset::getCreated */ public function testGetCreated() { // Setup $options = array('Created' => '2013-12-18', 'ParentIngestManifestId' => 'parent-manifest-id-3562'); $created = new \Datetime($options['Created']); $manifestAsset = IngestManifestAsset::createFromOptions($options); // Test $result = $manifestAsset->getCreated(); // Assert $this->assertEquals($created->getTimestamp(), $result->getTimestamp()); }
/** * Import a workspace list from a csv data. * * @param array $workspaces */ public function importWorkspaces(array $workspaces, $logger = null, $update = false) { $i = 0; $workspaceModelManager = $this->container->get('claroline.manager.workspace_model_manager'); foreach ($workspaces as $workspace) { ++$i; $this->om->startFlushSuite(); $endDate = null; $model = null; $name = $workspace[0]; $code = $workspace[1]; $isVisible = $workspace[2]; $selfRegistration = $workspace[3]; $registrationValidation = $workspace[4]; $selfUnregistration = $workspace[5]; if (isset($workspace[6]) && trim($workspace[6]) !== '') { $user = $this->om->getRepository('ClarolineCoreBundle:User')->findOneByUsername($workspace[6]); } else { $user = $this->container->get('security.context')->getToken()->getUser(); } if (isset($workspace[7])) { $model = $this->om->getRepository('ClarolineCoreBundle:Model\\WorkspaceModel')->findOneByName($workspace[7]); } if (isset($workspace[8])) { $endDate = new \DateTime(); $endDate->setTimestamp($workspace[8]); } if ($update) { $workspace = $this->getOneByCode($code); if (!$workspace) { //if the workspace doesn't exists, just keep going... continue; } if ($logger) { $logger('Updating ' . $code . ' (' . $i . '/' . count($workspaces) . ') ...'); } } else { $workspace = new Workspace(); } $workspace->setName($name); $workspace->setCode($code); $workspace->setDisplayable($isVisible); $workspace->setSelfRegistration($selfRegistration); $workspace->setSelfUnregistration($selfUnregistration); $workspace->setRegistrationValidation($registrationValidation); $workspace->setCreator($user); if ($endDate) { $workspace->setEndDate($endDate); } if (!$update) { if ($logger) { $logger('Creating ' . $code . ' (' . $i . '/' . count($workspaces) . ') ...'); } if ($model) { $guid = $this->ut->generateGuid(); $this->createWorkspace($workspace); $workspace->setGuid($guid); $date = new \Datetime(date('d-m-Y H:i')); $workspace->setCreationDate($date->getTimestamp()); $workspaceModelManager->addDataFromModel($model, $workspace, $user); } else { $template = new File($this->container->getParameter('claroline.param.default_template')); $this->container->get('claroline.manager.transfer_manager')->createWorkspace($workspace, $template, true); } } else { if ($model) { $workspaceModelManager->updateDataFromModel($model, $workspace); } } $this->om->persist($workspace); $logger('UOW: ' . $this->om->getUnitOfWork()->size()); if ($i % 100 === 0) { $this->om->forceFlush(); $user = $this->om->getRepository('ClarolineCoreBundle:User')->find($user->getId()); $this->om->merge($user); $this->om->refresh($user); } } $logger('Final flush...'); $this->om->endFlushSuite(); }