/** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria = new CDbCriteria(); if (isset($_GET["Audit"])) { $dH = new DateTimeHelper(); $dtFrom = $dH->getDateTimeFromUI($_GET["Audit"]["dateTimeFrom"]); $dtTo = $dH->getDateTimeFromUI($_GET["Audit"]["dateTimeTo"]); if ($desde !== false) { $criteria->addCondition('date_time >= ' . $dtFrom->getTimestamp()); } else { $criteria->addCondition('date_time >= ' . $dH->getDefaultStartRangeFilter("")->getTimestamp()); } if ($hasta !== false) { $criteria->addCondition('date_time <= ' . $dtTo->getTimestamp()); } else { $criteria->addCondition('date_time <= ' . $dH->getDefaultEndRangeFilter("audit")->getTimestamp()); } } $criteria->compare('object', $this->object, true); $criteria->compare('operation', $this->operation, true); $criteria->compare('description', $this->description, true); $criteria->compare('user', $this->user, true); return new CActiveDataProvider($this, array('criteria' => $criteria)); }
public function actionCreateEvent() { $transaction = Yii::app()->db->beginTransaction(); try { $dU = new DateTimeHelper(); $e = new Event(); $e->title = $_POST['title']; $e->body = $_POST['body']; $dt = $dU->getDateTimeFromUI($_POST['end']); $e->end = $dt->getTimestamp(); $dt = $dU->getDateTimeFromUI($_POST['start']); $e->start = $dt->getTimestamp(); $e->user_id = Yii::app()->user->id; if (!$e->save()) { $transaction->commit(); Response::ok(CJSON::encode(array("result" => "error", "message" => CJSON::encode($e->getErrors())))); } else { Response::ok(CJSON::encode(array("result" => "success", "message" => $e->id))); } } catch (Exception $exc) { $transaction->rollback(); Yii::log($exc->getMessage(), DBLog::LOG_LEVEL_ERROR); Response::error(CJSON::encode(array("result" => "error", "message" => Yii::app()->params["httpErrorCode500Message"]))); } }
/** * @param SproutSeo_SitemapModel $attributes * * @return mixed|null|string */ public function saveSitemap(SproutSeo_SitemapModel $attributes) { $row = array(); $isNew = false; if (isset($attributes->id) && substr($attributes->id, 0, 3) === "new") { $isNew = true; } if (!$isNew) { $row = craft()->db->createCommand()->select('*')->from('sproutseo_sitemap')->where('id=:id', array(':id' => $attributes->id))->queryRow(); } $model = SproutSeo_SitemapModel::populateModel($row); $model->id = !$isNew ? $attributes->id : null; $model->sectionId = isset($attributes->sectionId) ? $attributes->sectionId : null; $model->url = isset($attributes->url) ? $attributes->url : null; $model->priority = $attributes->priority; $model->changeFrequency = $attributes->changeFrequency; $model->enabled = $attributes->enabled == 'true' ? 1 : 0; $model->ping = $attributes->ping == 'true' ? 1 : 0; $model->dateUpdated = DateTimeHelper::currentTimeForDb(); $model->uid = StringHelper::UUID(); if ($isNew) { $model->dateCreated = DateTimeHelper::currentTimeForDb(); craft()->db->createCommand()->insert('sproutseo_sitemap', $model->getAttributes()); return craft()->db->lastInsertID; } else { $result = craft()->db->createCommand()->update('sproutseo_sitemap', $model->getAttributes(), 'id=:id', array(':id' => $model->id)); return $model->id; } }
/** * Fetches the installed package info from Elliott. */ public function actionFetchPackageInfo() { $this->requireAjaxRequest(); $etResponse = craft()->et->fetchPackageInfo(); if ($etResponse) { // Make sure we've got a valid license key (mismatched domain is OK for these purposes) if ($etResponse->licenseKeyStatus != LicenseKeyStatus::Invalid) { $packages = $etResponse->data; // Include which packages are actually licensed foreach ($etResponse->licensedPackages as $packageName) { $packages[$packageName]['licensed'] = true; } // Include which packages are in trial foreach ($etResponse->packageTrials as $packageName => $expiryDate) { $currentTime = DateTimeHelper::currentUTCDateTime(); $diff = $expiryDate - $currentTime->getTimestamp(); $daysLeft = round($diff / 86400); // 60 * 60 * 24 $packages[$packageName]['trial'] = true; $packages[$packageName]['daysLeftInTrial'] = $daysLeft; } $this->returnJson(array('success' => true, 'packages' => $packages)); } else { $this->returnErrorJson(Craft::t('Your license key is invalid.')); } } else { $this->returnErrorJson(Craft::t('Craft is unable to fetch package info at this time.')); } }
public function getTimeTotals($user_id, $time_range) { switch ($time_range) { case 'overall': $date_from = null; $date_to = null; break; case 'this_week': $days = DateTimeHelper::create()->getDaysOfWeek(date('W'), date('Y')); $date_from = date('Y-m-d 00:00:00', $days[1]); $date_to = date('Y-m-d 23:59:59', $days[7]); break; case 'last_week': $days = DateTimeHelper::create()->getDaysOfWeek(date('W') - 1, date('Y')); $date_from = date('Y-m-d 00:00:00', $days[1]); $date_to = date('Y-m-d 23:59:59', $days[7]); break; case 'this_month': $date_from = date('Y-m-d 00:00:00', mktime(00, 00, 00, date('m'), 01)); $date_to = date('Y-m-d 23:59:59', strtotime($date_from . '+1 MONTH -1 SECOND')); break; case 'last_month': $month = strtotime('last month'); $date_from = date('Y-m-d 00:00:00', mktime(00, 00, 00, date('m', $month), 01)); $date_to = date('Y-m-d 23:59:59', strtotime($date_from . '+1 MONTH -1 SECOND')); break; } $query = Doctrine_Query::create()->select('p.*, i.*, SUM(i.value) as total')->from('Project p')->where('i.user_id=?', $user_id)->innerJoin('p.TimeLogItems i')->groupBy('p.id')->orderBy('p.name'); if ($date_from != null && $date_to != null) { $query->andWhere('i.itemdate >= ? AND i.itemdate <= ?', array($date_from, $date_to)); } return $query->execute(); }
public function run() { $columnsParameters = array(array('dbField' => 'SupportDiscussionsEntity.idObjet', 'dtField' => 'objet', 'formatter' => function ($d, $row) { return \SupportObjetsHelper::getLibelle($d); }), array('dbField' => 'AdminsEntity.name', 'dtField' => 'compte', 'formatter' => function ($d, $row) { if ($this->isAdmin) { return $row["user"]; } else { return $d; } }), array('dbField' => 'AccountEntityUser.login', 'dtField' => 'user'), array('dbField' => 'SupportDiscussionsEntity.date', 'dtField' => 'date', 'formatter' => function ($d, $row) { return \DateTimeHelper::dateTimeToFormatedString($d, "d/m/Y"); }), array('dbField' => 'SupportDiscussionsEntity.dateDernierMessage', 'dtField' => 'lastMessage', 'formatter' => function ($d, $row) { $firstDate = date("Y-m-d"); $secondDate = $d->format('Y-m-d'); if ($firstDate == $secondDate) { return \DateTimeHelper::dateTimeToFormatedString($d, "H:i:s"); } else { return \DateTimeHelper::dateTimeToFormatedString($d); } }), array('dbField' => 'SupportMessagesEntity.id', 'dtField' => 'nonLuInDiscussion', 'formatter' => function ($d, $row) { if ($d === null) { return ""; } else { return "lineGreen"; } }), array('dbField' => 'SupportDiscussionsEntity.id', 'dtField' => 'actions', 'formatter' => function ($d, $row) { $varButton = '<a class="btn btn-material btn-primary btn-sm" onclick="DiscussionOpen(\'' . \Encryption::encrypt($d) . '\')"><i class="material-icons md-icon-message"></i></a>'; $varButton .= '<a class="btn btn-material btn-warning btn-sm" onclick="DiscussionArchivage(\'' . \Encryption::encrypt($d) . '\', 1)"><i class="material-icons md-icon-archive"></i></a>'; return '<div class="btn-toolbar">' . $varButton . "</div>"; })); $datatable = new \DataTable(); $datatable->setColumnsParameters($columnsParameters)->setRequest($_GET)->from("\\Site\\Entity\\SupportDiscussions", "SupportDiscussionsEntity")->innerJoin("\\Site\\Entity\\Admins", "AdminsEntity", "WITH", "AdminsEntity.idCompte = SupportDiscussionsEntity.idAdmin")->leftJoin("\\Account\\Entity\\Account", "AccountEntityUser", "WITH", "AccountEntityUser.id = SupportDiscussionsEntity.idCompte")->leftJoin("\\Site\\Entity\\SupportMessages", "SupportMessagesEntity", "WITH", "SupportMessagesEntity.idDiscussion = SupportDiscussionsEntity.id AND SupportMessagesEntity.etat = " . \SupportEtatMessageHelper::NON_LU . " AND SupportMessagesEntity.idCompte != " . $this->objAccount->getId() . "")->andWhere("SupportDiscussionsEntity.idCompte = " . $this->objAccount->getId() . " OR SupportDiscussionsEntity.idAdmin = " . $this->objAccount->getId() . "")->andWhere("SupportDiscussionsEntity.estArchive = 0")->groupBy("SupportDiscussionsEntity.id"); $datatable->getResult()->toJson(); }
/** * Returns the element's status. * * @return string|null */ public function getStatus() { $currentTime = DateTimeHelper::currentTimeStamp(); $startDate = $this->startDate ? $this->startDate->getTimestamp() : null; $endDate = $this->endDate ? $this->endDate->getTimestamp() : null; $pluginSettings = craft()->plugins->getPlugin('maintenance')->pluginSettings; $interval = $pluginSettings['maintenanceImminent']; $interval = DateInterval::createFromDateString($interval); $secondsInAdvance = (new DateTime('@0'))->add($interval)->getTimeStamp(); if (!$startDate) { return static::NONE; } if (!$this->blockCp && !$this->blockSite) { return static::DISABLED; } else { if ($startDate > $currentTime) { if ($startDate > $currentTime + $secondsInAdvance) { return static::PENDING; } else { return static::IMMINENT; } } else { if ($startDate <= $currentTime && (!$endDate || $endDate > $currentTime)) { return static::INPROGRESS; } else { if ($startDate <= $currentTime) { return static::COMPLETED; } } } } }
/** * @static * @return string */ public static function currentTimeForDb() { // Eventually this will return the time in the appropriate database format for MySQL, Postgre, etc. // For now, it's MySQL only. $date = DateTimeHelper::currentUTCDateTime(); return $date->format(DateTime::MYSQL_DATETIME, DateTime::UTC); }
public function run() { global $request; $em = \Shared\DoctrineHelper::getEntityManager(); $idCompte = $request->request->get("idCompte"); $idDiscussion = $request->request->get("idDiscussion"); $message = $request->request->get("message"); $objSupportMessage = new \Site\Entity\SupportMessages(); $objSupportMessage->setIdCompte($idCompte); $objSupportMessage->setIdDiscussion($idDiscussion); $objSupportMessage->setMessage($message); $objSupportMessage->setDate(new \DateTime(date("Y-m-d H:i:s"))); $objSupportMessage->setEtat(\SupportEtatMessageHelper::NON_LU); $objSupportMessage->setDatechangementEtat(new \DateTime(date("Y-m-d H:i:s"))); $objSupportMessage->setIp($this->ipAdresse); try { $objSupportDiscussion = \Site\SiteHelper::getSupportDiscussionsRepository()->find($idDiscussion); $objSupportDiscussion->setDateDernierMessage(new \DateTime(date("Y-m-d H:i:s"))); $em->persist($objSupportDiscussion); $em->persist($objSupportMessage); $em->flush(); if ($idCompte == $objSupportDiscussion->getIdAdmin()) { $objAccountJoueur = \Account\AccountHelper::getAccountRepository()->find($objSupportDiscussion->getIdCompte()); if ($objAccountJoueur !== null) { $template = $this->objTwig->loadTemplate("MessagerieMessageAdd.html5.twig"); $result = $template->render(["compte" => $objAccountJoueur->getLogin(), "objet" => \SupportObjetsHelper::getLibelle($objSupportDiscussion->getIdObjet())]); $subject = 'VamosMT2 - Réponse à votre ticket'; \EmailHelper::sendEmail($objAccountJoueur->getEmail(), $subject, $result); } } echo json_encode(["id" => $objSupportMessage->getId(), "date" => \DateTimeHelper::dateTimeToFormatedString($objSupportMessage->getDate(), "H:i"), "message" => nl2br($objSupportMessage->getMessage())]); } catch (Exception $ex) { } }
/** * Fetches and parses an RSS or Atom feed, and returns its items. * * Each element in the returned array will have the following keys: * * - **authors** – An array of the item’s authors, where each sub-element has the following keys: * - **name** – The author’s name * - **url** – The author’s URL * - **email** – The author’s email * - **categories** – An array of the item’s categories, where each sub-element has the following keys: * - **term** – The category’s term * - **scheme** – The category’s scheme * - **label** – The category’s label * - **content** – The item’s main content. * - **contributors** – An array of the item’s contributors, where each sub-element has the following keys: * - **name** – The contributor’s name * - **url** – The contributor’s URL * - **email** – The contributor’s email * - **date** – A {@link DateTime} object representing the item’s date. * - **dateUpdated** – A {@link DateTime} object representing the item’s last updated date. * - **permalink** – The item’s URL. * - **summary** – The item’s summary content. * - **title** – The item’s title. * * @param string $url The feed’s URL. * @param int $limit The maximum number of items to return. Default is 0 (no limit). * @param int $offset The number of items to skip. Defaults to 0. * @param string $cacheDuration Any valid [PHP time format](http://www.php.net/manual/en/datetime.formats.time.php). * * @return array|string The list of feed items. */ public function getFeedItems($url, $limit = 0, $offset = 0, $cacheDuration = null) { $items = array(); if (!extension_loaded('dom')) { Craft::log('Craft needs the PHP DOM extension (http://www.php.net/manual/en/book.dom.php) enabled to parse feeds.', LogLevel::Warning); return $items; } if (!$cacheDuration) { $cacheDuration = craft()->config->getCacheDuration(); } else { $cacheDuration = DateTimeHelper::timeFormatToSeconds($cacheDuration); } $feed = new \SimplePie(); $feed->set_feed_url($url); $feed->set_cache_location(craft()->path->getCachePath()); $feed->set_cache_duration($cacheDuration); $feed->init(); // Something went wrong. if ($feed->error()) { Craft: log('There was a problem parsing the feed: ' . $feed->error(), LogLevel::Warning); return array(); } foreach ($feed->get_items($offset, $limit) as $item) { $date = $item->get_date('U'); $dateUpdated = $item->get_updated_date('U'); $items[] = array('authors' => $this->_getItemAuthors($item->get_authors()), 'categories' => $this->_getItemCategories($item->get_categories()), 'content' => $item->get_content(true), 'contributors' => $this->_getItemAuthors($item->get_contributors()), 'date' => $date ? new DateTime('@' . $date) : null, 'dateUpdated' => $dateUpdated ? new DateTime('@' . $dateUpdated) : null, 'permalink' => $item->get_permalink(), 'summary' => $item->get_description(true), 'title' => $item->get_title(), 'enclosures' => $this->_getEnclosures($item->get_enclosures())); } return $items; }
/** * Downloads a file and cleans up old temporary assets */ public function actionDownloadFile() { // Clean up temp assets files that are more than a day old $fileResults = array(); $files = IOHelper::getFiles(craft()->path->getTempPath(), true); foreach ($files as $file) { $lastModifiedTime = IOHelper::getLastTimeModified($file, true); if (substr(IOHelper::getFileName($file, false, true), 0, 6) === "assets" && DateTimeHelper::currentTimeStamp() - $lastModifiedTime->getTimestamp() >= 86400) { IOHelper::deleteFile($file); } } // Sort out the file we want to download $id = craft()->request->getParam('id'); $criteria = craft()->elements->getCriteria(ElementType::Asset); $criteria->id = $id; $asset = $criteria->first(); if ($asset) { // Get a local copy of the file $sourceType = craft()->assetSources->getSourceTypeById($asset->sourceId); $localCopy = $sourceType->getLocalCopy($asset); // Send it to the browser craft()->request->sendFile($asset->filename, IOHelper::getFileContents($localCopy), array('forceDownload' => true)); craft()->end(); } }
private function _writeTableBody() { // die letzten 5 Flüge aus dem Hauptflugbuch werden ermittelt $flightlog = $this->_getData(); // Rückgabevariable initialisieren $html = ''; // alle gefunden Flüge werden durchlaufen und // anschließend in die Tabelle geschrieben foreach ($flightlog as $flight) { // Tabelleninhalt schreiben $html .= sprintf(' <tr> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> </tr> ', DateTimeHelper::DateFormat($flight['datum']), $flight['kennzeichen'], DateTimeHelper::TimeFormat($flight['startzeit']), DateTimeHelper::TimeFormat($flight['landezeit']), DateTimeHelper::MinutesToTimeFormat($flight['flugzeit'])); } // es wird geprüft, ob und wann die letzten 5 Flüge des angemeldeten // Mitgliedes durchgeführt wurden, sind keine Daten vorhanden, // dann wird eine entsprechende Meldung ausgegeben if (count($flightlog) == 0) { // Meldung, dass keine aktuellen Flüge vorhanden sind, zurückgeben $html = sprintf(' <tr> <td colspan="5" class="no-data">z. Zt. keine aktuellen Flüge</td> </tr> '); } // der Tabelleninhalt wird im HTML-Format zurückgegeben return $html; }
public function getJsonObject() { $ret = array('departureCity' => $this->getDepartureCity()->localRu, 'departureCityPre' => $this->getDepartureCity()->casePre, 'arrivalCity' => $this->getArrivalCity()->localRu, 'arrivalCityPre' => $this->getArrivalCity()->casePre, 'departureDate' => DateTimeHelper::formatForJs($this->departureDate), 'arrivalDate' => DateTimeHelper::formatForJs($this->getArrivalDate()), 'fullDuration' => $this->fullDuration, 'flightParts' => array()); foreach ($this->flightParts as $flightPart) { $ret['flightParts'][] = $flightPart->getJsonObject(); } return $ret; }
/** * Get appendix for an URL based on it's Source caching settings. * * @param BaseAssetSourceType $source * @param AssetFileModel $file * * @return string */ public static function getUrlAppendix(BaseAssetSourceType $source, AssetFileModel $file) { $appendix = ''; if (!empty($source->getSettings()->expires) && DateTimeHelper::isValidIntervalString($source->getSettings()->expires)) { $appendix = '?mtime=' . $file->dateModified->format("YmdHis"); } return $appendix; }
/** * Returns the next active announcement. * * @param string $timeInAdvance * * @return AnnouncementModel */ public function getNextAnnouncement($timeInAdvance = '0') { $time = DateTimeHelper::currentUTCDateTime(); $time->modify('+' . $timeInAdvance); $announcementRecord = craft()->db->createCommand()->select('*')->from('maintenance_announcements')->where(array('and', array('or', 'blockSite = 1', 'blockCp = 1'), 'startDate <= :time', array('or', 'endDate >= :now', 'endDate IS NULL')), array(':now' => DateTimeHelper::formatTimeForDb(), ':time' => DateTimeHelper::formatTimeForDb($time)))->order('startDate desc')->queryRow(); if ($announcementRecord) { return Maintenance_AnnouncementModel::populateModel($announcementRecord); } }
/** * @param $endpoint * @param int $timeout * @param int $connectTimeout * * @return Et */ public function __construct($endpoint, $timeout = 30, $connectTimeout = 2) { $endpoint .= craft()->config->get('endpointSuffix'); $this->_endpoint = $endpoint; $this->_timeout = $timeout; $this->_connectTimeout = $connectTimeout; $this->_model = new EtModel(array('licenseKey' => $this->_getLicenseKey(), 'requestUrl' => craft()->request->getHostInfo() . craft()->request->getUrl(), 'requestIp' => craft()->request->getIpAddress(), 'requestTime' => DateTimeHelper::currentTimeStamp(), 'requestPort' => craft()->request->getPort(), 'localBuild' => CRAFT_BUILD, 'localVersion' => CRAFT_VERSION, 'localEdition' => craft()->getEdition(), 'userEmail' => craft()->userSession->getUser()->email, 'track' => CRAFT_TRACK, 'serverInfo' => array('extensions' => get_loaded_extensions(), 'phpVersion' => PHP_VERSION, 'mySqlVersion' => craft()->db->getServerVersion()))); $this->_userAgent = 'Craft/' . craft()->getVersion() . '.' . craft()->getBuild(); }
/** * Set sql file header * * @return null */ private function _processHeader() { $header = '-- Generated by Craft ' . $this->_currentVersion . ' on ' . DateTimeHelper::nice(DateTimeHelper::currentTimeStamp()) . '.' . PHP_EOL . PHP_EOL; $header .= '--' . PHP_EOL . '-- Disable foreign key checks and autocommit.' . PHP_EOL . '--' . PHP_EOL . PHP_EOL; $header .= 'SET FOREIGN_KEY_CHECKS = 0;' . PHP_EOL; $header .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . PHP_EOL; $header .= 'SET AUTOCOMMIT = 0;' . PHP_EOL; $header .= 'SET NAMES utf8;' . PHP_EOL . PHP_EOL; IOHelper::writeToFile($this->_filePath, $header, true, true); }
/** * Manages all models. */ public function actionAdmin() { $model = new Audit('search'); $model->unsetAttributes(); if (isset($_GET['Audit'])) { $model->attributes = $_GET['Audit']; } $dH = new DateTimeHelper(); if (isset($_GET["Audit"]["dateTimeFrom"]) && strcmp($_GET["Audit"]["dateTimeFrom"], "") !== 0) { $model->dateTimeFrom = $_GET["Audit"]["dateTimeFrom"]; } else { $model->dateTimeFrom = $dH->getDefaultStartRangeFilter("")->format(Yii::app()->params["dateTimeDisplayFormat"]); } if (isset($_GET["Audit"]["dateTimeTo"]) && strcmp($_GET["Audit"]["dateTimeTo"], "") !== 0) { $model->dateTimeTo = $_GET["Audit"]["dateTimeTo"]; } else { $model->dateTimeTo = $dH->getDefaultEndRangeFilter("")->format(Yii::app()->params["dateTimeDisplayFormat"]); } $this->render('admin', array('model' => $model)); }
public static function EndLog(\Puzzlout\Framework\Core\Application $app, $guid) { $logs = Logger::GetLogs($app->user()); $log = $logs[$guid]; $log->setF_log_end(Logger::GetTime()); $log->setF_log_execution_time(($log->f_log_end() - $log->f_log_start()) * 1000); $log->setF_log_start(DateTimeHelper::GetDateTimeWithMs($log->f_log_start())); $log->setF_log_end(DateTimeHelper::GetDateTimeWithMs($log->f_log_end())); Logger::AddLogToDatabase($app, $log); Logger::StoreLogs($app->user(), $logs); }
public function run() { $columnsParameters = array(array('dbField' => 'LogsItemshopAchatsEntity.date', 'dtField' => 'date', 'formatter' => function ($d, $row) { return \DateTimeHelper::dateTimeToFormatedString($d); }), array('dbField' => 'LogsItemshopAchatsEntity.item', 'dtField' => 'article'), array('dbField' => 'LogsItemshopAchatsEntity.quantite', 'filterLevel' => 'strict', 'dtField' => 'quantite'), array('dbField' => 'LogsItemshopAchatsEntity.devise', 'dtField' => 'devise'), array('dbField' => 'LogsItemshopAchatsEntity.prix', 'filterLevel' => 'strict', 'dtField' => 'prix', 'formatter' => function ($d, $row) { return number_format($d, 0, '.', ',') . "<span style='position:relative; top:2px;'>" . \FonctionsUtiles::findIconDevise($row["devise"]) . "</span>"; }), array('dbField' => 'AccountEntity.login', 'dtField' => 'compte'), array('dbField' => 'LogsItemshopAchatsEntity.resultat', 'dtField' => 'result')); $datatable = new \DataTable(); $datatable->setColumnsParameters($columnsParameters)->setRequest($_GET)->from("\\Site\\Entity\\LogsItemshopAchats", "LogsItemshopAchatsEntity")->leftJoin("\\Account\\Entity\\Account", "AccountEntity", "WITH", "AccountEntity.id = LogsItemshopAchatsEntity.idCompte"); $datatable->getResult()->toJson(); }
/** * @param $object * @param $attribute * * @return null */ protected function validateAttribute($object, $attribute) { $value = $object->{$attribute}; if ($value) { if (!$value instanceof \DateTime) { if (!DateTimeHelper::isValidTimeStamp((string) $value)) { $message = Craft::t('“{object}->{attribute}” must be a DateTime object or a valid Unix timestamp.', array('object' => get_class($object), 'attribute' => $attribute)); $this->addError($object, $attribute, $message); } } } }
/** * @param $endpoint * @param int $timeout * @param int $connectTimeout * * @return Et */ public function __construct($endpoint, $timeout = 30, $connectTimeout = 30) { $endpoint .= craft()->config->get('endpointSuffix'); $this->_endpoint = $endpoint; $this->_timeout = $timeout; $this->_connectTimeout = $connectTimeout; // There can be a race condition after an update from older Craft versions where they lose session // and another call to elliott is made during cleanup. $userEmail = craft()->userSession->getUser() ? craft()->userSession->getUser()->email : ''; $this->_model = new EtModel(array('licenseKey' => $this->_getLicenseKey(), 'pluginLicenseKeys' => $this->_getPluginLicenseKeys(), 'requestUrl' => craft()->request->getHostInfo() . craft()->request->getUrl(), 'requestIp' => craft()->request->getIpAddress(), 'requestTime' => DateTimeHelper::currentTimeStamp(), 'requestPort' => craft()->request->getPort(), 'localBuild' => CRAFT_BUILD, 'localVersion' => CRAFT_VERSION, 'localEdition' => craft()->getEdition(), 'userEmail' => $userEmail, 'track' => CRAFT_TRACK, 'showBeta' => craft()->config->get('showBetaUpdates'), 'serverInfo' => array('extensions' => get_loaded_extensions(), 'phpVersion' => PHP_VERSION, 'mySqlVersion' => craft()->db->getServerVersion(), 'proc' => function_exists('proc_open') ? 1 : 0))); $this->_userAgent = 'Craft/' . craft()->getVersion() . '.' . craft()->getBuild(); }
public function actionGetAllEvents() { $events = Event::model()->findAll(array('select' => array('id', 'title', 'startDate'))); $response = array(); foreach ($events as $event) { $element = array(); $element['id'] = $event->id; $element['title'] = $event->title; $element['startDate'] = DateTimeHelper::formatForEventForm($event->startDate); $response[] = $element; } $this->send($response); }
/** * Shuns a CP alert for 24 hours. * * @return null */ public function actionShunCpAlert() { $this->requireAjaxRequest(); craft()->userSession->requirePermission('accessCp'); $message = craft()->request->getRequiredPost('message'); $user = craft()->userSession->getUser(); $currentTime = DateTimeHelper::currentUTCDateTime(); $tomorrow = $currentTime->add(new DateInterval('P1D')); if (craft()->users->shunMessageForUser($user->id, $message, $tomorrow)) { $this->returnJson(array('success' => true)); } else { $this->returnErrorJson(Craft::t('An unknown error occurred.')); } }
public function run() { $columnsParameters = array(array('dbField' => 'ActualitesEntity.date', 'dtField' => 'date', 'formatter' => function ($d, $row) { return \DateTimeHelper::dateTimeToFormatedString($d); }), array('dbField' => 'ActualitesEntity.titre', 'dtField' => 'titre'), array('dbField' => 'ActualitesEntity.contenu', 'dtField' => 'message', 'formatter' => function ($d, $row) { return \FonctionsUtiles::Raccourcissement_Chaine($d, 50); }), array('dbField' => 'AccountEntity.login', 'dtField' => 'compte'), array('dbField' => 'ActualitesEntity.id', 'dtField' => 'actions', 'formatter' => function ($d, $row) { $varButton = '<a class="btn btn-material btn-primary btn-sm" data-featherlight="ajax" href="pages/Admin/GererNewsEdit.php?mode=mod&idNews=' . $d . '"><i class="material-icons md-icon-edit"></i></a>'; $varButton .= '<a class="btn btn-material btn-danger btn-sm" onclick="SuppressionNews(' . $d . ')"><i class="material-icons md-icon-delete"></i></a>'; return '<div class="btn-toolbar">' . $varButton . "</div>"; })); $datatable = new \DataTable(); $datatable->setColumnsParameters($columnsParameters)->setRequest($_GET)->from("\\Site\\Entity\\Actualites", "ActualitesEntity")->leftJoin("\\Account\\Entity\\Account", "AccountEntity", "WITH", "AccountEntity.id = ActualitesEntity.idCompte"); $datatable->getResult()->toJson(); }
/** * Logs a new deprecation error. * * @param string $key * @param string $message * * @return bool */ public function log($key, $message) { $log = new DeprecationErrorModel(); $log->key = $key; $log->message = $message; $log->lastOccurrence = DateTimeHelper::currentTimeForDb(); $log->template = craft()->request->isSiteRequest() ? craft()->templates->getRenderingTemplate() : null; // Everything else requires the stack trace $this->_populateLogWithStackTraceData($log); // Don't log the same key/fingerprint twice in the same request if (!isset($this->_fingerprints[$log->key]) || !in_array($log->fingerprint, $this->_fingerprints[$log->key])) { craft()->db->createCommand()->insertOrUpdate(static::$_tableName, array('key' => $log->key, 'fingerprint' => $log->fingerprint), array('lastOccurrence' => DateTimeHelper::formatTimeForDb($log->lastOccurrence), 'file' => $log->file, 'line' => $log->line, 'class' => $log->class, 'method' => $log->method, 'template' => $log->template, 'templateLine' => $log->templateLine, 'message' => $log->message, 'traces' => JsonHelper::encode($log->traces))); $this->_fingerprints[$key][] = $log->fingerprint; } return true; }
public function actionRegister() { $model = new User('register'); // Uncomment the following line if AJAX validation is needed $this->performAjaxValidation($model); if (isset($_POST['User'])) { $model->setAttributes($_POST['User']); $model->birthday = DateTimeHelper::convertToDTStringFromPOSTForFieldName('birthday', $_POST); //captcha validating require_once Yii::app()->basePath . '/vendor/recaptchalib.php'; $privatekey = "6LfXBe8SAAAAAA7fOOWIfyfmvWbIjk-s15UFfGec"; $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { $error = $resp->error; if ($resp->error == 'incorrect-captcha-sol') { $error = '確認碼不正確'; } $this->render('register', array('model' => $model, 'captchaError' => $error)); return; } else { // Your code here to handle a successful verification /** store the password for the athentication user * Since the password will be hashed once it is saved */ $rawPassword = $model->password; if ($model->validate()) { if ($model->save()) { $identity = new UserIdentity($model->user_name, $rawPassword); $duration = 3600 * 24 * 30; // 30 days $identity->authenticate(); if (Yii::app()->user->login($identity, $duration)) { Yii::app()->user->setFlash(FlashMsg::SUCCESS, "歡迎加入!"); } else { Yii::app()->user->setFlash(FlashMsg::WARNING, "歡迎加入! 請在登入頁面登入"); } $this->redirect(array('index')); } else { Yii::app()->user->setFlash(FlashMsg::ERROR, "創建使用者失敗"); } } else { $model->purgePassword(); } } } $this->render('register', array('model' => $model, 'captchaError' => '')); }
/** * @inheritDoc BaseModel::defineAttributes() * * @return array */ protected function defineAttributes() { // The client license key. $attributes['licenseKey'] = AttributeType::String; // The license key status. Set by the server response. $attributes['licenseKeyStatus'] = AttributeType::String; // The edition that Craft is licensed to use $attributes['licensedEdition'] = array(AttributeType::Enum, 'values' => array(Craft::Personal, Craft::Client, Craft::Pro)); // The domain that the license is associated with $attributes['licensedDomain'] = AttributeType::String; // Whether Craft is running for a domain that's eligible to be used in Edition Test Mode $attributes['editionTestableDomain'] = AttributeType::Bool; // The installed plugin license keys. $attributes['pluginLicenseKeys'] = AttributeType::Mixed; // The plugins' license key statuses. Set by the server response. $attributes['pluginLicenseKeyStatuses'] = AttributeType::Mixed; // Extra arbitrary data to send to the server. $attributes['data'] = AttributeType::Mixed; // The url making the request. $attributes['requestUrl'] = array(AttributeType::String, 'default' => ''); // The IP address making the request. $attributes['requestIp'] = array(AttributeType::String, 'default' => '1.1.1.1'); // The time the request was made. $attributes['requestTime'] = array(AttributeType::DateTime, 'default' => DateTimeHelper::currentTimeForDb()); // The port number the request comes from. $attributes['requestPort'] = AttributeType::String; // The local version number. $attributes['localVersion'] = array(AttributeType::String, 'required' => true); // The local build number. $attributes['localBuild'] = array(AttributeType::Number, 'required' => true); // The local edition. $attributes['localEdition'] = array(AttributeType::String, 'required' => true); // The currently logged in user's email address. $attributes['userEmail'] = AttributeType::Email; // The track this install is on. Not required for backwards compatibility. $attributes['track'] = array(AttributeType::String); // Whether or not to show beta releases. $attributes['showBeta'] = AttributeType::Bool; // Any errors to return; $attributes['errors'] = AttributeType::Mixed; // Any additional server info to include. $attributes['serverInfo'] = AttributeType::Mixed; // The context of the request. Either 'craft' or a plugin handle. $attributes['handle'] = array(AttributeType::String, 'default' => 'craft', 'required' => true); return $attributes; }
private function _writeTableBody() { // die anstehenden Geburtstage werden ermittelt $birthdayList = $this->_getBirthdayList(); // Rückgabevariable initialisieren $html = ''; // alle gefunden Flugbetriebsdienste des Jahres werden // durchlaufen und anschließend in die Tabelle geschrieben foreach ($birthdayList as $birthday) { // prüfen ob eine gültige eMailadresse hinterlegt ist if (!empty($birthday['email'])) { // die eMailadresse wird mit einem Brief-Icon // versehen und als ein Link "mailto:" gesetzt $birthday['email'] = sprintf(' <a href="mailto:%s"> <img src="../media/images/email_icon.gif" alt="" title="%s" /> </a> ', $birthday['email'], $birthday['email']); } // Tabelleninhalt schreiben $html .= sprintf(' <tr> <td><img src="../media/images/1354017068_cake.png" alt="" />%s %s</td> <td>%s. %s.</td> <td>%d</td> <td>%s</td> </tr> ', $birthday['vorname'], $birthday['nachname'], DateTimeHelper::DayOfMonth($birthday['geburtstag']), DateTimeHelper::MonthShortName($birthday['geburtstag']), $birthday['alter'], $birthday['email']); } // es wird geprüft, ob im aktuellen Zeitraum überhaupt Geburtstage von // Mitgliedern anstehenen, ist dies nicht der Fall und es sind keine // Daten vorhanden, dann wird eine entsprechende Meldung ausgegeben if (count($birthdayList) == 0) { // Meldung, dass keine aktuellen Geburtstag anliegen, zurückgeben $html = sprintf(' <tr> <td colspan="4" class="no-data">Es wurden keine passenden Daten gefunden!</td> </tr> '); } // der Tabelleninhalt wird im HTML-Format zurückgegeben return $html; }
/** * @inheritDoc BaseElementModel::getStatus() * * @return string|null */ public function getStatus() { $status = parent::getStatus(); if ($status == static::ENABLED && $this->postDate) { $currentTime = DateTimeHelper::currentTimeStamp(); $postDate = $this->postDate->getTimestamp(); $expiryDate = $this->expiryDate ? $this->expiryDate->getTimestamp() : null; if ($postDate <= $currentTime && (!$expiryDate || $expiryDate > $currentTime)) { return static::LIVE; } else { if ($postDate > $currentTime) { return static::PENDING; } else { return static::EXPIRED; } } } return $status; }