Exemplo n.º 1
0
 public function actionShow($key, $id)
 {
     $pageModel = Media::model()->findByPk($id);
     $this->pageTitle .= ' - Фото та відео - ' . $pageModel->getTitle();
     /** @var $cs CClientScript */
     Yii::app()->getClientScript()->registerMetaTag($pageModel->getMetaDescription(), 'description')->registerMetaTag($pageModel->getMetaKeyWords(), 'keywords');
     $lastNews = Media::model()->last(Yii::app()->params['frontend']['itemsPerPage'])->notIn(array($id))->findAll();
     $this->breadcrumbs = array('Головна' => $this->createUrl('site/index'), 'Фото та відео' => $this->createUrl('index'), $pageModel->getTitle(100, TRUE));
     $this->render('show', array('pageModel' => $pageModel, 'lastModels' => $lastNews, 'archiveYears' => Media::getYearsForArchive()));
 }
Exemplo n.º 2
0
 private function deleteMedia($id)
 {
     /** @var $model Media [ ] */
     $model = Media::model()->findByPk($id);
     $this->assertNotEmpty($model, " media record does not exist");
     $this->assertTrue($model->delete(), " record not deleted");
     foreach ($model->getImageSizes() as $imageSize) {
         $this->assertEquals(false, $model->getFullPath($imageSize), $imageSize . " is not deleted");
     }
 }
Exemplo n.º 3
0
 /**
  * Called after removing media or changing the filename field. Checks for existing references
  * to filename and deletes file if none exist.
  */
 private function collectGarbage(array $exclude = array())
 {
     if (!in_array($this->getPath(), $exclude) && file_exists($this->getPath())) {
         $media = Media::model()->findByAttributes(array('uploadedBy' => $this->uploadedBy, 'fileName' => $this->fileName));
         // Only delete the file if it is the last media object
         // To use it.
         if (!$media) {
             unlink($this->getPath());
         }
     }
 }
Exemplo n.º 4
0
 public static function openBodyTag(array $preferences, array $htmlOptions = array())
 {
     $cs = Yii::app()->clientScript;
     $baseUrl = $cs->baseUrl;
     $fullscreen = $cs->fullscreen;
     $style = '';
     $classes = 'enable-search-bar-modes';
     $noBorders = false;
     if ($preferences != null && $preferences['backgroundColor']) {
         $style .= 'background-color:#' . $preferences['backgroundColor'] . ';';
     }
     if ($preferences != null && $preferences['backgroundImg']) {
         if (Yii::app()->user->isGuest) {
             $media = Media::model()->findByAttributes(array('id' => $preferences['backgroundImg']));
             if ($media) {
                 $mediaUrl = $media->getPublicUrl();
             }
         } else {
             $mediaUrl = $baseUrl . Yii::app()->request->scriptUrl . '/media/getFile/' . $preferences['backgroundImg'];
         }
         if (isset($mediaUrl)) {
             $style .= 'background-image:url(' . $mediaUrl . ');';
             $classes .= ' custom-background-image';
         }
         switch ($bgTiling = $preferences['backgroundTiling']) {
             case 'repeat-x':
             case 'repeat-y':
             case 'repeat':
                 $style .= 'background-repeat:' . $bgTiling . ';';
                 break;
             case 'center':
                 $style .= 'background-repeat:no-repeat;background-position:center center;';
                 break;
             case 'stretch':
             default:
                 $style .= 'background-attachment:fixed;background-size:cover;';
                 $noBorders = true;
         }
     }
     if ($noBorders) {
         $classes .= ' no-borders';
     }
     if ($fullscreen) {
         $classes .= ' no-widgets';
     } else {
         $classes .= ' show-widgets';
     }
     if (!RESPONSIVE_LAYOUT) {
         $classes .= ' disable-mobile-layout';
     }
     $classes .= ' not-mobile-body';
     $htmlOptions = self::mergeHtmlOptions(array('class' => $classes, 'style' => $style), $htmlOptions);
     return self::openTag('body', $htmlOptions);
 }
	/**
	 * Load configuration that cannot be put in config/main
	 */
	public function beginRequest() {
	
		$prof=Profile::model()->findByPk(Yii::app()->user->getId());
		if (isset($prof->language))
			$this->owner->language=$prof->language;
                else{
                    $adminProf=ProfileChild::model()->findByPk(1);
                    $this->owner->language=$adminProf->language;
                }
		if(isset($prof->timeZone) && $prof->timeZone!='')
			date_default_timezone_set($prof->timeZone);
		$adminProf=ProfileChild::model()->findByAttributes(array('username'=>'admin'));
		$logo=Media::model()->findByAttributes(array('associationId'=>$adminProf->id,'associationType'=>'logo'));
		if(isset($logo)){
			$this->owner->params->logo=$logo->fileName;
		}
		
		$admin = CActiveRecord::model('Admin')->findByPk(1);
		$this->owner->params->currency = $admin->currency;
    }
Exemplo n.º 6
0
 public function afterDelete()
 {
     parent::afterDelete();
     // Reset path if name was changed:
     $this->_path = null;
     if (file_exists($this->getPath())) {
         $media = Media::model()->findByAttributes(array('uploadedBy' => $this->uploadedBy, 'fileName' => $this->fileName));
         // Only delete the file if it is the last media object
         // To use it.
         if (!$media) {
             unlink($this->getPath());
         }
     }
     // if theme is deleted which is default, unset default theme setting
     if ($this->id === Yii::app()->settings->defaultTheme) {
         Yii::app()->settings->defaultTheme = null;
         Yii::app()->settings->enforceDefaultTheme = false;
         Yii::app()->settings->save();
     }
 }
Exemplo n.º 7
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Topics();
     $fileCreation = false;
     if (isset($_FILES['upload']) || isset($_POST['Topics'])) {
         $data = array();
         $topicText = null;
         if (isset($_FILES['upload'])) {
             $fileCreation = true;
             $data = array('name' => $_POST['topicName']);
             $topicText = $_POST['topicText'];
         } else {
             if (isset($_POST['Topics'])) {
                 $data = $_POST['Topics'];
                 $topicText = $_POST['TopicReplies']['text'];
             }
         }
         $data['text'] = $topicText;
         $model->setX2Fields($data, false, true);
         if (isset($_POST['x2ajax'])) {
             $ajaxErrors = $this->quickCreate($model);
         } else {
             if ($model->save()) {
                 if ($fileCreation) {
                     $media = new Media();
                     $username = Yii::app()->user->getName();
                     // file uploaded through form
                     $temp = CUploadedFile::getInstanceByName('upload');
                     if ($temp && ($tempName = $temp->getTempName()) && !empty($tempName)) {
                         $name = $temp->getName();
                         $name = str_replace(' ', '_', $name);
                         $check = Media::model()->findAllByAttributes(array('fileName' => $name));
                         // rename file if there name conflicts by suffixing "(n)"
                         if (count($check) != 0) {
                             $count = 1;
                             $newName = $name;
                             $arr = explode('.', $name);
                             $name = $arr[0];
                             while (count($check) != 0) {
                                 $newName = $name . '(' . $count . ').' . $temp->getExtensionName();
                                 $check = Media::model()->findAllByAttributes(array('fileName' => $newName));
                                 $count++;
                             }
                             $name = $newName;
                         }
                     }
                     if (FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$name}")) {
                         $media->associationType = 'topicReply';
                         $media->associationId = $model->originalPost->id;
                         $media->uploadedBy = $username;
                         $media->createDate = time();
                         $media->lastUpdated = time();
                         $media->fileName = $name;
                         $media->mimetype = $temp->type;
                         if ($media->save()) {
                             echo $model->id;
                             Yii::app()->end();
                         }
                     }
                 } else {
                     $this->redirect(array('view', 'id' => $model->id));
                 }
             } elseif ($model->hasErrors('text')) {
                 Yii::app()->user->setFlash('error', 'Original post text cannot be blank.');
             }
         }
     }
     if (isset($_POST['x2ajax']) || isset($_FILES['upload'])) {
         $this->renderInlineForm($model);
     } else {
         $this->render('create', array('model' => $model));
     }
 }
Exemplo n.º 8
0
 public function actionPreviewTheme($themeName)
 {
     $theme = Media::model()->findByAttributes(array('associationType' => 'theme ', 'fileName' => $themeName));
     if ($theme) {
         $settings = CJSON::decode($theme->description);
         ThemeGenerator::previewTheme($settings);
     }
 }
Exemplo n.º 9
0
 public function run()
 {
     if (Yii::app()->user->isGuest) {
         Yii::app()->controller->redirect(Yii::app()->controller->createUrl('/site/login'));
     }
     $this->attachBehaviors($this->behaviors);
     // Safety net of handlers - they ensure that errors can be caught and seen easily:
     $scenario = 'custom';
     if (empty($this->model)) {
         $model = new InlineEmail();
     } else {
         $model = $this->model;
     }
     if (isset($_POST['contactFlag'])) {
         $model->contactFlag = $_POST['contactFlag'];
     }
     $makeEvent = isset($_GET['skipEvent']) ? !(bool) $_GET['skipEvent'] : 1;
     // Check to see if the user is requesting a new template
     if (isset($_GET['template'])) {
         $scenario = 'template';
     }
     $model->setScenario($scenario);
     $attachments = array();
     if (isset($_POST['InlineEmail'])) {
         // This could indicate either a template change or a form submission.
         $model->attributes = $_POST['InlineEmail'];
         // Prepare attachments that may have been uploaded on-the-fly (?)
         $mediaLibraryUsed = false;
         // is there an attachment from the media library?
         if (isset($_POST['AttachmentFiles'], $_POST['AttachmentFiles']['id'], $_POST['AttachmentFiles']['types'])) {
             $ids = $_POST['AttachmentFiles']['id'];
             $types = $_POST['AttachmentFiles']['types'];
             $attachments = array();
             for ($i = 0; $i < count($ids); $i++) {
                 $type = $types[$i];
                 switch ($type) {
                     case 'temp':
                         // attachment is a temp file
                         $tempFile = TempFile::model()->findByPk($ids[$i]);
                         $attachments[] = array('filename' => $tempFile->name, 'folder' => $tempFile->folder, 'type' => $type, 'id' => $tempFile->id);
                         break;
                     case 'media':
                         // attachment is from media library
                         $mediaLibraryUsed = true;
                         $media = Media::model()->findByPk($ids[$i]);
                         $attachments[] = array('filename' => $media->fileName, 'folder' => $media->uploadedBy, 'type' => $type, 'id' => $media->id);
                         break;
                     default:
                         throw new CException('Invalid attachment type: ' . $type);
                 }
             }
         }
         $model->attachments = $attachments;
         // Validate/prepare the body, and send if no problems occur:
         $sendStatus = array_fill_keys(array('code', 'message'), '');
         $failed = false;
         $message = '';
         $postReplace = isset($_GET['postReplace']) ? $_GET['postReplace'] : 0;
         if (isset($_GET['loadTemplate'])) {
             // A special override for when it's not possible to include the template in $_POST
             $model->template = $_GET['loadTemplate'];
         }
         if ($model->prepareBody($postReplace)) {
             if ($scenario != 'template') {
                 // Sending the email, not merely requesting a template change
                 //
                 // First check that the user has permission to use the
                 // specified credentials:
                 if ($model->credId != Credentials::LEGACY_ID) {
                     if (!Yii::app()->user->checkAccess('CredentialsSelect', array('model' => $model->credentials))) {
                         $this->respond(Yii::t('app', 'Did not send email because you do not have ' . 'permission to use the specified credentials.'), 1);
                     }
                 }
                 $sendStatus = $model->send($makeEvent);
                 // $sendStatus = array('code'=>'200','message'=>'sent (testing)');
                 $failed = $sendStatus['code'] != '200';
                 $message = $sendStatus['message'];
             } else {
                 if ($model->modelName == 'Quote' && empty($model->template)) {
                     // Fill in the gap with the default / "semi-legacy" quotes view
                     $model->message = $this->controller->renderPartial('application.modules.quotes.views.quotes.print', array('model' => $model->targetModel, 'email' => true), true);
                     // Add a linebreak at the beginning for user-entered notes in the email:
                     $model->insertInBody('<br />', 1);
                 }
             }
         }
         // Populate response data:
         $modelHasErrors = $model->hasErrors();
         $failed = $failed || $modelHasErrors;
         $response = array('scenario' => $scenario, 'sendStatus' => $sendStatus, 'attributes' => $model->attributes, 'modelErrors' => $model->errors, 'modelHasErrors' => $modelHasErrors, 'modelErrorHtml' => CHtml::errorSummary($model, Yii::t('app', "Please fix the following errors:"), null, array('style' => 'margin-bottom: 5px;')));
         if ($scenario == 'template') {
             // There's a chance the inline email form is switching gears into
             // quote mode, in which case we need to include templates and
             // insertable attributes for setting it all up properly:
             $response['insertableAttributes'] = $model->insertableAttributes;
             $templates = array(0 => Yii::t('docs', 'Custom Message')) + Docs::getEmailTemplates($model->modelName == 'Quote' ? 'quote' : 'email', $_POST['associationType']);
             $response['templateList'] = array();
             foreach ($templates as $id => $templateName) {
                 $response['templateList'][] = array('id' => $id, 'name' => $templateName);
             }
         }
         $this->mergeResponse($response);
         $this->respond($message, $failed);
     } else {
         $this->respond(Yii::t('app', 'Inline email model missing from the request to the server.'), true);
     }
 }
Exemplo n.º 10
0
 /**
  * Load dynamic app configuration.
  *
  * Per the onBeginRequest key in the array returned by {@link events()},
  * this method will be called when the request has begun. It allows for
  * many extra configuration tasks to be run on a per-request basis
  * without having to extend {@link Yii} and override its methods.
  */
 public function beginRequest()
 {
     // About the "noSession" property/variable:
     //
     // This variable, if true, indicates that the application is running in
     // the context of either an API call or a console command, in which case
     // there would not be the typical authenticated user and session
     // variables one would need in a web request
     //
     // It's necessary because originally this method was written with
     // absolutely no regard for compatibility with the API or Yii console,
     // and thus certain lines of code that make references to the usual web
     // environment with cookie-based authentication (which would fail in
     // those cases) needed to be kept inside of conditional statements that
     // are skipped over if in the console/API.
     $this->owner->params->noSession = $this->owner->params->noSession || strpos($this->owner->request->getPathInfo(), 'api/') === 0 || strpos($this->owner->request->getPathInfo(), 'api2/') === 0;
     $noSession = $this->owner->params->noSession;
     if (!$noSession) {
         if ($this->owner->request->getPathInfo() == 'notifications/get') {
             // skip all the loading if this is a chat/notification update
             Yii::import('application.components.util.AuxLib');
             Yii::import('application.models.Roles');
             Yii::import('application.components.X2AuthManager');
             Yii::import('application.components.X2Html');
             Yii::import('application.components.X2WebUser');
             Yii::import('application.components.sortableWidget.*');
             Yii::import('application.components.sortableWidget.profileWidgets.*');
             Yii::import('application.components.sortableWidget.recordViewWidgets.*');
             Yii::import('application.components.X2Settings.*');
             Yii::import('application.components.X2MessageSource');
             Yii::import('application.components.Formatter');
             Yii::import('application.components.X2Html');
             Yii::import('application.components.JSONEmbeddedModelFieldsBehavior');
             Yii::import('application.components.TransformedFieldStorageBehavior');
             Yii::import('application.components.EncryptedFieldsBehavior');
             Yii::import('application.components.permissions.*');
             Yii::import('application.models.Modules');
             if (!$this->owner->user->getIsGuest()) {
                 $profData = $this->owner->db->createCommand()->select('timeZone, language')->from('x2_profile')->where('id=' . $this->owner->user->getId())->queryRow();
             }
             // set the timezone to the admin's
             if (isset($profData)) {
                 if (isset($profData['timeZone'])) {
                     $timezone = $profData['timeZone'];
                 }
                 if (isset($profData['language'])) {
                     $language = $profData['language'];
                 } else {
                 }
             }
             if (!isset($timezone)) {
                 $timezone = 'UTC';
             }
             if (!isset($language)) {
                 $language = 'en';
             }
             date_default_timezone_set($timezone);
             $this->owner->language = $language;
             Yii::import('application.models.X2Model');
             Yii::import('application.models.Dropdowns');
             Yii::import('application.models.Admin');
             $this->cryptInit();
             // Yii::import('application.models.*');
             // foreach(scandir('protected/modules') as $module){
             // if(file_exists('protected/modules/'.$module.'/register.php'))
             // Yii::import('application.modules.'.$module.'.models.*');
             // }
             return;
         }
     } else {
         Yii::import('application.models.Profile');
         Yii::import('application.components.sortableWidget.*');
         Yii::import('application.components.X2Settings.*');
         Yii::import('application.components.TransformedFieldStorageBehavior');
         // Set time zone based on the default value
         date_default_timezone_set(Profile::model()->tableSchema->getColumn('timeZone')->defaultValue);
     }
     $this->importDirectories();
     $this->cryptInit();
     if (YII_DEBUG) {
         $this->owner->params->timer = new TimerUtil();
     }
     $this->owner->messages->onMissingTranslation = array(new TranslationLogger(), 'log');
     // Set profile
     //
     // Get the Administrator's and the current user's profile.
     $adminProf = Profile::model()->findByPk(1);
     $this->owner->params->adminProfile = $adminProf;
     if (!$noSession) {
         // Typical web session:
         $notGuest = !$this->owner->user->getIsGuest();
         if ($notGuest) {
             $this->owner->params->profile = X2Model::model('Profile')->findByAttributes(array('username' => $this->owner->user->getName()));
             $this->setSuModel($this->owner->params->profile->user);
         } else {
             $this->owner->params->profile = Profile::model()->getGuestProfile();
         }
     } else {
         // Use the admin profile as the user profile.
         //
         // If a different profile is desired in an API call or console
         // command, a different profile should be loaded.
         //
         // Using "admin" as the default profile should not affect
         // permissions (that's what the "suModel" property is for). It is
         // merely to account for cases where there is a reference to the
         // "profile" property of some model or component class that would
         // break the application outside the scope of a web request with a
         // session and cookie-based authentication.
         $notGuest = false;
         $this->owner->params->profile = $adminProf;
         $userModel = $this->owner->params->profile->user;
         $this->setSuModel($userModel instanceof User ? $userModel : User::model()->findByPk(1));
     }
     // Set session variables
     if (!$noSession) {
         $sessionId = isset($_SESSION['sessionId']) ? $_SESSION['sessionId'] : session_id();
         $session = X2Model::model('Session')->findByPk($sessionId);
         if (!empty($this->owner->params->profile)) {
             $_SESSION['fullscreen'] = $this->owner->params->profile->fullscreen;
         }
         if (!($this->owner->request->getPathInfo() == 'site/getEvents')) {
             if ($notGuest) {
                 $this->owner->user->setReturnUrl($this->owner->request->requestUri);
                 if ($session != null) {
                     $timeout = Roles::getUserTimeout($this->owner->user->getId());
                     if ($session->lastUpdated + $timeout < time()) {
                         SessionLog::logSession($this->owner->user->getName(), $sessionId, 'activeTimeout');
                         $session->delete();
                         $this->owner->user->logout(false);
                         $this->_suModel = null;
                         $this->_suID = null;
                         $this->setUserAccessParameters(null);
                     } else {
                         // Print a warning message
                         if ($this->owner->session['debugEmailWarning']) {
                             $this->owner->session['debugEmailWarning'] = 0;
                             $this->owner->user->setFlash('admin.debugEmailMode', Yii::t('app', 'Note, email debugging mode ' . 'is enabled. Emails will not ' . 'actually be delivered.'));
                         }
                         $session->lastUpdated = time();
                         $session->update(array('lastUpdated'));
                         $this->owner->params->sessionStatus = $session->status;
                     }
                 } else {
                     $this->owner->user->logout(false);
                 }
             } else {
                 // Guest
                 $this->setUserAccessParameters(null);
             }
         }
     }
     // Configure logos
     if (!($logo = $this->owner->cache['x2Power'])) {
         $logo = 'data:image/png;base64,' . base64_encode(file_get_contents(implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, '..', 'images', 'powered_by_x2engine.png'))));
         $this->owner->cache['x2Power'] = $logo;
     }
     $this->owner->params->x2Power = $logo;
     $logo = Media::model()->findByAttributes(array('associationId' => 1, 'associationType' => 'logo'));
     if (isset($logo)) {
         $this->owner->params->logo = $logo->fileName;
     }
     // Set currency and load currency symbols
     $this->owner->params->currency = $this->settings->currency;
     $locale = $this->owner->locale;
     $curSyms = array();
     foreach ($this->owner->params->supportedCurrencies as $curCode) {
         $curSyms[$curCode] = $locale->getCurrencySymbol($curCode);
     }
     $this->owner->params->supportedCurrencySymbols = $curSyms;
     // Code to symbol
     // Set language
     if (!empty($this->owner->params->profile->language)) {
         $this->owner->language = $this->owner->params->profile->language;
     } else {
         if (isset($adminProf)) {
             $this->owner->language = $adminProf->language;
         }
     }
     // Set timezone
     if (!empty($this->owner->params->profile->timeZone)) {
         date_default_timezone_set($this->owner->params->profile->timeZone);
     } elseif (!empty($adminProf->timeZone)) {
         date_default_timezone_set($adminProf->timeZone);
     } else {
         date_default_timezone_set('UTC');
     }
     setlocale(LC_ALL, 'en_US.UTF-8');
     // Set base path and theme path globals for JS (web UI only)
     if (!$noSession) {
         $this->checkForMobileDevice();
         $this->checkResponsiveLayout();
         if ($notGuest) {
             $profile = $this->owner->params->profile;
             if (isset($profile)) {
                 $yiiString = $this->getJSGlobalsSetupScript($profile);
             } else {
                 $yiiString = $this->getJSGlobalsSetupScript();
             }
             if (!$this->owner->request->isAjaxRequest) {
                 Yii::app()->clientScript->registerScript(sprintf('%x', crc32(Yii::app()->name)), base64_decode('dmFyIF8weDFhNzk9WyJceDc1XHg2RVx4NjRceDY1XHg2Nlx4NjlceDZFXHg2NVx4NjQiLCJceDZDXHg2R' . 'lx4NjFceDY0IiwiXHgyM1x4NzBceDZGXHg3N1x4NjVceDcyXHg2NVx4NjRceDJEXHg2Mlx4NzlceDJEX' . 'Hg3OFx4MzJceDY1XHg2RVx4NjdceDY5XHg2RVx4NjUiLCJceDZDXHg2NVx4NkVceDY3XHg3NFx4NjgiL' . 'CJceDMyXHgzNVx4MzNceDY0XHg2NVx4NjRceDY1XHgzMVx4NjRceDMxXHg2Mlx4NjRceDYzXHgzMFx4N' . 'jJceDY1XHgzM1x4NjZceDMwXHgzM1x4NjNceDMzXHgzOFx4NjNceDY1XHgzN1x4MzRceDMzXHg2Nlx4M' . 'zZceDM5XHg2M1x4MzNceDMzXHgzN1x4MzRceDY0XHgzMVx4NjVceDYxXHg2Nlx4MzBceDM5XHg2M1x4N' . 'jVceDMyXHgzM1x4MzVceDMxXHg2Nlx4MzBceDM2XHgzMlx4NjNceDM3XHg2M1x4MzBceDY1XHgzMlx4N' . 'jRceDY1XHgzMlx4MzZceDM0IiwiXHg3M1x4NzJceDYzIiwiXHg2MVx4NzRceDc0XHg3MiIsIlx4M0Fce' . 'Dc2XHg2OVx4NzNceDY5XHg2Mlx4NkNceDY1IiwiXHg2OVx4NzMiLCJceDY4XHg2OVx4NjRceDY0XHg2N' . 'Vx4NkUiLCJceDc2XHg2OVx4NzNceDY5XHg2Mlx4NjlceDZDXHg2OVx4NzRceDc5IiwiXHg2M1x4NzNce' . 'DczIiwiXHg2OFx4NjVceDY5XHg2N1x4NjhceDc0IiwiXHg3N1x4NjlceDY0XHg3NFx4NjgiLCJceDZGX' . 'Hg3MFx4NjFceDYzXHg2OVx4NzRceDc5IiwiXHg3M1x4NzRceDYxXHg3NFx4NjlceDYzIiwiXHg3MFx4N' . 'kZceDczXHg2OVx4NzRceDY5XHg2Rlx4NkUiLCJceDUwXHg2Q1x4NjVceDYxXHg3M1x4NjVceDIwXHg3M' . 'Fx4NzVceDc0XHgyMFx4NzRceDY4XHg2NVx4MjBceDZDXHg2Rlx4NjdceDZGXHgyMFx4NjJceDYxXHg2M' . '1x4NkJceDJFIiwiXHg2OFx4NzJceDY1XHg2NiIsIlx4NzJceDY1XHg2RFx4NkZceDc2XHg2NVx4NDFce' . 'Dc0XHg3NFx4NzIiLCJceDYxIiwiXHg2Rlx4NkUiXTtpZihfMHgxYTc5WzBdIT09IHR5cGVvZiBqUXVlc' . 'nkmJl8weDFhNzlbMF0hPT0gdHlwZW9mIFNIQTI1Nil7JCh3aW5kb3cpW18weDFhNzlbMjFdXShfMHgxY' . 'Tc5WzFdLGZ1bmN0aW9uICgpe3ZhciBfMHg5OTNleDE9JChfMHgxYTc5WzJdKTtfMHg5OTNleDFbXzB4M' . 'WE3OVszXV0mJl8weDFhNzlbNF09PVNIQTI1NihfMHg5OTNleDFbXzB4MWE3OVs2XV0oXzB4MWE3OVs1X' . 'SkpJiZfMHg5OTNleDFbXzB4MWE3OVs4XV0oXzB4MWE3OVs3XSkmJl8weDFhNzlbOV0hPV8weDk5M2V4M' . 'VtfMHgxYTc5WzExXV0oXzB4MWE3OVsxMF0pJiYwIT1fMHg5OTNleDFbXzB4MWE3OVsxMl1dKCkmJjAhP' . 'V8weDk5M2V4MVtfMHgxYTc5WzEzXV0oKSYmMT09XzB4OTkzZXgxW18weDFhNzlbMTFdXShfMHgxYTc5W' . 'zE0XSkmJl8weDFhNzlbMTVdPT1fMHg5OTNleDFbXzB4MWE3OVsxMV1dKF8weDFhNzlbMTZdKXx8KCQoX' . 'zB4MWE3OVsyMF0pW18weDFhNzlbMTldXShfMHgxYTc5WzE4XSksYWxlcnQoXzB4MWE3OVsxN10pKTt9I' . 'Ck7fQo='));
             }
         } else {
             $yiiString = $this->getJSGlobalsSetupScript();
         }
         $this->owner->clientScript->registerScript('setParams', $yiiString, CClientScript::POS_HEAD);
         $cs = $this->owner->clientScript;
         $baseUrl = $this->owner->request->baseUrl;
         $jsVersion = '?' . $this->owner->params->buildDate;
         /**
          * To be restored when JavaScript minification is added to the build process:
          * $cs->scriptMap=array(
          * 'backgroundImage.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'json2.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'layout.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'media.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'modernizr.custom.66175.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'publisher.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * //'relationships.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'tags.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'translator.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'widgets.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * 'x2forms.js'=>$baseUrl.'/js/all.min.js'.$jsVersion,
          * ); */
     }
 }
Exemplo n.º 11
0
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model=Media::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
Exemplo n.º 12
0
Yii::app()->clientScript->registerPackage('X2CSS');
Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl() . '/js/profileSettings.js', CClientScript::POS_END);
Yii::app()->clientScript->registerCssFile(Yii::app()->theme->baseUrl . '/css/profileSettings.css');
Tours::tips(array(array('content' => Yii::t('app', 'You can disable tips like this by unchecking this box.'), 'target' => '#Profile_showTours')));
$preferences = $model->theme;
$miscLayoutSettings = $model->miscLayoutSettings;
$passVariablesToClientScript = "\n    x2.profileSettings.checkerImagePath = '" . Yii::app()->theme->getBaseUrl() . "/images/checkers.gif';\n    x2.profileSettings.createThemeHint = '" . Yii::t('profile', 'Save your current theme settings as a predefined theme.') . "';\n    x2.profileSettings.saveThemeHint = '" . Yii::t('profile', 'Update the settings of the currently selected predefined theme.') . "';\n    x2.profileSettings.normalizedUnhideTagUrl = '" . CHtml::normalizeUrl(array("/profile/unhideTag")) . "';\n    x2.profileSettings.translations = {\n        themeImportDialogTitle: '" . Yii::t('profile', 'Import a Theme') . "',\n        close: '" . Yii::t('app', 'close') . "',\n    };\n    x2.profileSettings.uploadedByAttrs = {};\n";
// pass array of predefined theme uploadedBy attributes to client
foreach ($myThemes->data as $theme) {
    $passVariablesToClientScript .= "x2.profileSettings.uploadedByAttrs['" . $theme->id . "'] = '" . $theme->uploadedBy . "';";
}
Yii::app()->clientScript->registerScript('passVariablesToClientScript', $passVariablesToClientScript, CClientScript::POS_END);
// If the user was redirected from /site/upload and the "useId" parameter is
// available, set the background to that so they get instant feedback
if (isset($_GET['bgId'])) {
    $media = Media::model()->findByPk($_GET['bgId']);
    if ($media instanceof Media) {
        Yii::app()->clientScript->registerScript('setBackgroundToUploaded', '$("select#backgroundImg").val(' . $media->id . ').trigger("change");', CClientScript::POS_READY);
    }
}
?>

<?php 
$form = $this->beginWidget('X2ActiveForm', array('id' => 'settings-form', 'enableAjaxValidation' => false));
echo $form->errorSummary($model);
?>

<div id="profile-settings" class="form">
    <?php 
echo X2Html::getFlashes();
?>
Exemplo n.º 13
0
 /**
  * Magic getter for {@link actionHeader}
  *
  * Composes an informative header for the action record.
  *
  * @return type
  */
 public function getActionHeader()
 {
     if (!isset($this->_actionHeader)) {
         $recipientContacts = $this->recipientContacts;
         // Add email headers to the top of the action description's body
         // so that the resulting recorded action has all the info of the
         // original email.
         $fromString = $this->from['address'];
         if (!empty($this->from['name'])) {
             $fromString = '"' . $this->from['name'] . '" <' . $fromString . '>';
         }
         $header = CHtml::tag('strong', array(), Yii::t('app', 'Subject: ')) . CHtml::encode($this->subject) . '<br />';
         $header .= CHtml::tag('strong', array(), Yii::t('app', 'From: ')) . CHtml::encode($fromString) . '<br />';
         // Put in recipient lists, and if any correspond to contacts, make links
         // to them in place of their names.
         foreach (array('to', 'cc', 'bcc') as $recList) {
             if (!empty($this->mailingList[$recList])) {
                 $header .= CHtml::tag('strong', array(), ucfirst($recList) . ': ');
                 foreach ($this->mailingList[$recList] as $target) {
                     if ($recipientContacts[$target[1]] != null) {
                         $header .= $recipientContacts[$target[1]]->link;
                     } else {
                         $header .= CHtml::encode("\"{$target[0]}\"");
                     }
                     $header .= CHtml::encode(" <{$target[1]}>,");
                 }
                 $header = rtrim($header, ', ') . '<br />';
             }
         }
         // Include special quote information if it's a quote being issued or emailed to a random contact
         if ($this->modelName == 'Quote') {
             $header .= '<br /><hr />';
             $header .= CHtml::tag('strong', array(), Yii::t('quotes', $this->targetModel->type == 'invoice' ? 'Invoice' : 'Quote')) . ':';
             $header .= ' ' . $this->targetModel->link . ($this->targetModel->status ? ' (' . $this->targetModel->status . '), ' : ' ') . Yii::t('app', 'Created') . ' ' . $this->targetModel->renderAttribute('createDate') . ';';
             $header .= ' ' . Yii::t('app', 'Updated') . ' ' . $this->targetModel->renderAttribute('lastUpdated') . ' by ' . $this->userProfile->fullName . '; ';
             $header .= ' ' . Yii::t('quotes', 'Expires') . ' ' . $this->targetModel->renderAttribute('expirationDate');
             $header .= '<br />';
         }
         // Attachments info
         if (!empty($this->attachments)) {
             $header .= '<br /><hr />';
             $header .= CHtml::tag('strong', array(), Yii::t('media', 'Attachments:')) . "<br />";
             $i = 0;
             foreach ($this->attachments as $attachment) {
                 if ($i++) {
                     $header .= '<br />';
                 }
                 if ($attachment['type'] === 'temp') {
                     // attempt to convert temporary file to media record
                     if ($this->modelId && $this->modelName) {
                         $associationId = $this->modelId;
                         $associationType = X2Model::getAssociationType($this->modelName);
                     } elseif ($contact = reset($recipientContacts)) {
                         $associationId = $contact->id;
                         $associationType = 'contacts';
                     }
                     if (isset($associationId) && ($media = $attachment['model']->convertToMedia(array('associationType' => $associationType, 'associationId' => $associationId)))) {
                         $attachment['type'] = 'media';
                         $attachment['id'] = $media->id;
                     }
                 }
                 if ($attachment['type'] === 'media' && ($media = Media::model()->findByPk($attachment['id']))) {
                     $header .= $media->getLink() . '&nbsp;|&nbsp;' . $media->getDownloadLink();
                 } else {
                     $header .= CHtml::tag('span', array('class' => 'email-attachment-text'), $attachment['filename']) . '<br />';
                 }
             }
         }
         $this->_actionHeader = $header . '<br /><hr />';
     }
     return $this->_actionHeader;
 }
Exemplo n.º 14
0
        ?>
-media" class="user-media-list">
                    <?php 
        foreach ($userMediaItems as $item) {
            if (!$item['private'] || $admin) {
                $baseId = "{$user['username']}-media-id-{$item['id']}";
                $jsSelectorId = CJSON::encode("#{$baseId}");
                $propertyId = addslashes($baseId);
                $desc = CHtml::encode($item['description']);
                echo '<span class="x2-pillbox media-item">';
                $path = Media::getFilePath($item['uploadedBy'], $item['fileName']);
                $filename = $item['drive'] ? $item['name'] : $item['fileName'];
                if (mb_strlen($filename, 'UTF-8') > 35) {
                    $filename = mb_substr($filename, 0, 32, 'UTF-8') . '…';
                }
                echo CHtml::link($filename, array('/media', 'view' => $item['id']), array('class' => 'x2-link media media-library-item' . (Media::isImageExt($item['fileName']) ? ' image-file' : ''), 'id' => $baseId, 'data-url' => Media::model()->findByPk($item['id'])->getPublicUrl()));
                echo '</span>';
                if (Media::isImageExt($item['fileName'])) {
                    $imageLink = Media::getFileUrl($path);
                    $image = CHtml::image($imageLink, '', array('class' => 'media-hover-image'));
                    $imageStr = CJSON::encode($image);
                    if ($item['description']) {
                        $content = CJSON::encode("<span style=\"max-width: 200px;\">{$image} {$desc}</span>");
                        $imageTooltips .= "\$({$jsSelectorId}).qtip({content: {$content}, position: {my: 'top right', at: 'bottom left'}});\n";
                    } else {
                        $imageTooltips .= "\$({$jsSelectorId}).qtip({content: {$imageStr}, position: {my: 'top right', at: 'bottom left'}});\n";
                    }
                } else {
                    if ($item['description']) {
                        $content = CJSON::encode($desc);
                        $imageTooltips .= "\$({$jsSelectorId}).qtip({content: {$content}, position: {my: 'top right', at: 'bottom left'}});\n";
Exemplo n.º 15
0
 public function actionChangeArea()
 {
     if (!isset($_POST['id'])) {
         return;
     }
     $model = Media::model()->findByPk($_POST['id']);
     if (!$model) {
         return;
     }
     $model->med_dims = $_POST['value'];
     if ($model->save()) {
         echo 'done';
     } else {
         echo 'error';
     }
 }
Exemplo n.º 16
0
 /**
  * 获取反对票数量
  */
 public function getMediaCount()
 {
     return Media::model()->count("mediaableEntityId=:entityId and value<=0", array(':entityId' => $this->getOwner()->entityId));
 }
Exemplo n.º 17
0
 /**
  * @param int $count
  * @return Deal
  */
 public function epcCount($count = 0)
 {
     $this->getDbCriteria()->mergeWith(array('select' => '(select COUNT(med_id) FROM ' . Media::model()->tableName() . " WHERE med_row = t.dea_id AND med_type = 'EPC' group by t.dea_id) AS epcCount", 'having' => 'epcCount = 0 OR epcCount is NULL', 'limit' => 1));
     return $this;
 }
Exemplo n.º 18
0
    echo Icon::CROSS_SYMBOL;
    ?>
</span>
					<img src="<?php 
    echo $value->getThumbImageURIPath();
    ?>
" class="media-file"
						 data-id="<?php 
    echo $value->med_id;
    ?>
">

					<div class="image-actions">
						<div class="action">
							<?php 
    echo CHtml::dropDownList('med_title_' . $value->med_id, $value->med_title, Media::model()->getPhotoTitles(), array('data-id' => $value->med_id, 'class' => 'input-block titleChanger'));
    ?>
</div>
					</div>
				</div>
			<?php 
}
?>
		</div>
	</div>
</div>

<script type="text/javascript">
	var jcrop_api;
	(function () {
		$(".sortable").sortable({
Exemplo n.º 19
0
 public function getAttachments()
 {
     if (is_null($this->_attachments)) {
         $this->_attachments = Media::model()->findAllByAttributes(array('associationType' => 'topicReply', 'associationId' => $this->id));
     }
     return $this->_attachments;
 }
Exemplo n.º 20
0
 public function actionQtip($id)
 {
     $model = Media::model()->findByPk($id);
     $this->renderPartial('qtip', array('model' => $model));
 }
Exemplo n.º 21
0
	public function actionToggleDefaultLogo() {
		
		$adminProf=ProfileChild::model()->findByAttributes(array('username'=>'admin'));
		$logo=Media::model()->findByAttributes(array('associationId'=>$adminProf->id,'associationType'=>'logo'));
		if(!isset($logo)) {

			$logo=new Media;
			$logo->associationType='logo';
			$name='yourlogohere.png';
			$logo->associationId=$adminProf->id;
			$logo->fileName='uploads/logos/'.$name;

			if($logo->save()) {

			}
		} else {
			$logo->delete();
		}
		$this->redirect(array('index'));
	}
Exemplo n.º 22
0
 public function resolveNameConflicts()
 {
     $found = (int) Media::model()->countByAttributes(array('fileName' => $this->fileName));
     // rename file if there name conflicts by suffixing "(n)"
     if ($found) {
         $count = 1;
         $newName = $this->fileName;
         $ext = CFileHelper::getExtension($newName);
         $base = preg_replace('/\\.' . preg_quote($ext) . '$/', '', $newName);
         while ($found) {
             $newName = "{$base}({$count}).{$ext}";
             $found = (int) Media::model()->countByAttributes(array('fileName' => $newName));
             $count++;
         }
         $this->fileName = $newName;
     }
 }
Exemplo n.º 23
0
 /**
  * Registers css for responsive title bar. Since title bar logo width can change, the
  * media query that determines the appearance of the title bar must be set in accordance
  * with the width of the currently uploaded logo.
  */
 private function registerResponsiveTitleBarCss()
 {
     $logo = Media::model()->findByAttributes(array('associationId' => 1, 'associationType' => 'logo'));
     if (isset($logo)) {
         $dimensions = CJSON::decode($logo->resolveDimensions());
         if (is_array($dimensions)) {
             $imgWidth = floor($dimensions['width'] * (30 / $dimensions['height']));
             Yii::app()->clientScript->registerScript('logoWidthScript', "\n                if (typeof x2 === 'undefined') x2 = {};\n                x2.logoWidth = " . $imgWidth . ";\n                ", CClientScript::POS_HEAD);
         }
     }
     if (isset($imgWidth)) {
         $threshold = 915 + $imgWidth;
     } else {
         $threshold = 915;
     }
     Yii::app()->clientScript->registerResponsiveCss('responsiveTitleBar', "\n        /*\n        Step between full title bar and mobile title bar. Search bar minimizes and expands to make\n        room for user menu links\n        */\n        @media (max-width: " . $threshold . "px) {\n            #search-bar-box {\n                display: none;\n                width: 180px;\n            }\n            #search-bar button.x2-button {\n                border-radius: 3px 3px 3px 3px;\n                -moz-border-radius: 3px 3px 3px 3px;\n                -webkit-border-radius: 3px 3px 3px 3px;\n                -o-border-radius: 3px 3px 3px 3px;\n            }\n        }\n\n        @media (min-width: " . $threshold . "px) {\n            #user-menu > li {\n                display: block !important;\n            }\n            #search-bar-box {\n                display: block !important;\n            }\n        }\n        ");
 }
Exemplo n.º 24
0
?>
>
        <div id="header-inner">
            <div id="main-menu-bar">
                <div id='show-left-menu-button'>
                    <i class='fa fa-bars'></i>
                </div>
                <a href="<?php 
echo $isGuest ? $this->createUrl('/site/login') : $this->createUrl('/profile/view', array('id' => Yii::app()->user->getId()));
?>
"
                 id='search-bar-title' class='special'>
                <?php 
$custom = Yii::app()->params->logo !== 'uploads/protected/logos/yourlogohere.png';
if ($custom) {
    $media = Media::model()->findByAttributes(array('associationType' => 'logo'));
    if ($media) {
        echo CHtml::image($media->getPublicUrl(), Yii::app()->settings->appName, array('id' => 'your-logo', 'class' => 'custom-logo'));
    }
} else {
    echo X2Html::logo('menu', array('id' => 'your-logo', 'class' => 'default-logo'));
}
?>
                </a>
                <div id='top-menus-container'>
                <div id='top-menus-container-inner'>
                <?php 
//render main menu items
$this->widget('zii.widgets.CMenu', array('id' => 'main-menu', 'encodeLabel' => false, 'htmlOptions' => array('class' => 'main-menu'), 'items' => $menuItems));
//render user menu items if logged in
if (!$isGuest) {
Exemplo n.º 25
0
 public function afterSave($evt)
 {
     // file attribute value is expected to be either an id of old associated media or
     // an instance of CUploadedFile. Can also be an array containing either.
     $fileAttribute = $this->fileAttribute;
     $transaction = Yii::app()->db->beginTransaction();
     try {
         $files = ArrayUtil::coerceToArray($this->owner->{$fileAttribute});
         // remove old associated media with ids not found in file attribute
         $resubmittedMediaIds = array();
         foreach ($files as $file) {
             if (!$file instanceof CUploadedFile && is_numeric($file)) {
                 $resubmittedMediaIds[] = (int) $file;
             }
         }
         $associatedMedia = Media::model()->findAllByAttributes(array('associationType' => $this->associationType, 'associationId' => $this->getAssociationId()));
         foreach ($associatedMedia as $media) {
             if (!in_array((int) $media->id, $resubmittedMediaIds, true)) {
                 $media->delete();
             }
         }
         // save uploaded files as associated media
         foreach ($files as $file) {
             $this->saveAssociatedMedia($file);
         }
         $transaction->commit();
     } catch (CException $e) {
         $transaction->rollback();
     }
 }
 /**
  * Load configuration that cannot be put in config/main
  */
 public function beginRequest()
 {
     $t0 = microtime(true);
     if ($this->owner->request->getPathInfo() == 'notifications/getMessages') {
         // skip all the loading if this is a chat/notification update
         $timezone = $this->owner->db->createCommand()->select('timeZone')->from('x2_profile')->where('id=1')->queryScalar();
         // set the timezone to the admin's
         if (!isset($timezone)) {
             $timezone = 'UTC';
         }
         date_default_timezone_set($timezone);
         return;
     }
     Yii::import('application.controllers.x2base');
     Yii::import('application.models.*');
     Yii::import('application.components.*');
     // Yii::import('application.components.ERememberFiltersBehavior');
     // Yii::import('application.components.EButtonColumnWithClearFilters');
     // $this->owner->messages->forceTranslation = true;
     $this->owner->messages->onMissingTranslation = array(new TranslationLogger(), 'log');
     $this->owner->params->admin = CActiveRecord::model('Admin')->findByPk(1);
     $this->owner->params->profile = CActiveRecord::model('ProfileChild')->findByPk($this->owner->user->getId());
     // die( var_dump($this->owner->request->getPathInfo())); //->getRoute();
     if (!$this->owner->user->isGuest) {
         // use the admin's profile as default
         $this->owner->params->profile = CActiveRecord::model('ProfileChild')->findByPk($this->owner->user->getId());
         $session = Session::model()->findByAttributes(array('user' => $this->owner->user->getName()));
         if (isset($session)) {
             if (time() - $session->lastUpdated > $this->owner->params->admin->timeout) {
                 $session->delete();
                 $this->owner->user->logout();
             } else {
                 $session->lastUpdated = time();
                 $session->save();
             }
         } else {
             $this->owner->user->logout();
             // $this->redirect(Yii::app()->controller->createUrl('site/logout'));
         }
         if (!is_null($this->owner->user->getId()) && $this->owner->user->getName() != 'admin') {
             $this->owner->params->roles = $this->owner->db->createCommand()->select('roleId')->from('x2_role_to_user')->where('type="user" AND userId=' . $this->owner->user->getId())->queryColumn();
             $this->owner->params->groups = $this->owner->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . $this->owner->user->getId())->queryColumn();
             $groupRoles = Yii::app()->db->createCommand()->select('x2_role_to_user.roleId')->from('x2_group_to_user')->join('x2_role_to_user', 'x2_role_to_user.userId=x2_group_to_user.groupId AND x2_group_to_user.userId="' . Yii::app()->user->getId() . '" AND type="group"')->queryColumn();
             // foreach($this->owner->params->groups as $groupId) {		// lookup roles for all the user's groups
             // $groupRoles += $this->owner->db->createCommand()
             // ->select('roleId')
             // ->from('x2_role_to_user')
             // ->where('type="group" AND userId='.$groupId)->queryColumn();
             // }
             $this->owner->params->roles = array_unique($this->owner->params->roles + $groupRoles);
             // combine all the roles, remove duplicates
         }
     }
     $modules = $this->owner->modules;
     $arr = array();
     foreach (scandir('protected/modules') as $module) {
         if (file_exists("protected/modules/{$module}/register.php")) {
             $arr[$module] = ucfirst($module);
             Yii::import("application.modules.{$module}.models.*");
         }
     }
     foreach ($arr as $key => $module) {
         $record = Modules::model()->findByAttributes(array('name' => $key));
         if (isset($record) && $record->visible) {
             $modules[] = $key;
         }
     }
     $this->owner->setModules($modules);
     $adminProf = ProfileChild::model()->findByPk(1);
     // set currency
     $this->owner->params->currency = $this->owner->params->admin->currency;
     // set language
     if (!empty($this->owner->params->profile->language)) {
         $this->owner->language = $this->owner->params->profile->language;
     } else {
         if (isset($adminProf)) {
             $this->owner->language = $adminProf->language;
         } else {
             $this->owner->language = '';
         }
     }
     // set timezone
     if (!empty($this->owner->params->profile->timeZone)) {
         date_default_timezone_set($this->owner->params->profile->timeZone);
     } elseif (!empty($adminProf->timeZone)) {
         date_default_timezone_set($adminProf->timeZone);
     } else {
         date_default_timezone_set('UTC');
     }
     $logo = Media::model()->findByAttributes(array('associationId' => 1, 'associationType' => 'logo'));
     if (isset($logo)) {
         $this->owner->params->logo = $logo->fileName;
     }
     setlocale(LC_ALL, 'en_US.UTF-8');
     // die(microtime(true)-$t0);
 }
Exemplo n.º 27
0
 /**
  * Upload contact profile picture from Facebook.
  */
 public function actionUploadProfilePicture()
 {
     if (isset($_POST['photourl'])) {
         $photourl = $_POST['photourl'];
         $name = 'profile_picture_' . $_POST['associationId'] . '.jpg';
         $model = new Media();
         $check = Media::model()->findAllByAttributes(array('fileName' => $name));
         if (count($check) != 0) {
             $count = 1;
             $newName = $name;
             $arr = explode('.', $name);
             $name = $arr[0];
             while (count($check) != 0) {
                 $newName = $name . '(' . $count . ').jpg';
                 $check = Media::model()->findAllByAttributes(array('fileName' => $newName));
                 $count++;
             }
             $name = $newName;
         }
         $model->associationId = $_POST['associationId'];
         $model->associationType = $_POST['type'];
         $model->createDate = time();
         $model->fileName = $name;
         // download and save picture
         $img = FileUtil::ccopy($photourl, "uploads/{$name}");
         $model->save();
         // put picture into new action
         $note = new Actions();
         $note->createDate = time();
         $note->dueDate = time();
         $note->completeDate = time();
         $note->complete = 'Yes';
         $note->visibility = '1';
         $note->completedBy = "Web Lead";
         $note->assignedTo = 'Anyone';
         $note->type = 'attachment';
         $note->associationId = $_POST['associationId'];
         $note->associationType = $_POST['type'];
         $association = $this->getAssociation($note->associationType, $note->associationId);
         if ($association != null) {
             $note->associationName = $association->name;
         }
         $note->actionDescription = $model->fileName . ':' . $model->id;
         if ($note->save()) {
         } else {
             unlink('uploads/' . $name);
         }
         $this->redirect(array($model->associationType . '/' . $model->associationId));
     }
 }
Exemplo n.º 28
0
	public function actionUpload() {
		if(isset($_FILES['upload'])) {
			$model=new Media;
			$temp = CUploadedFile::getInstanceByName('upload');
			$name=$temp->getName();
			$name=str_replace(' ','_',$name);
			$check=Media::model()->findAllByAttributes(array('fileName'=>$name));
			if(count($check)!=0) {
				$count=1;
				$newName=$name;
				$arr=explode('.',$name);
				$name=$arr[0];
				while(count($check)!=0){
					$newName=$name.'('.$count.').'.$temp->getExtensionName();
					$check=Media::model()->findAllByAttributes(array('fileName'=>$newName));
					$count++;
				}
				$name=$newName;
			}
			if($temp->saveAs('uploads/'.$name)) {
				$model->associationId=$_POST['associationId'];
				$model->associationType=$_POST['type'];
				$model->uploadedBy=Yii::app()->user->getName();
				$model->createDate=time();
				$model->fileName=$name;
				if($model->save()){
					
				}
				if($model->associationType=='feed') {
					$soc = new Social;
					$soc->user = Yii::app()->user->getName();
					$soc->data = Yii::t('app','Attached file: ').
					$soc->type = 'feed';
					$soc->timestamp = time();
					$soc->lastUpdated = time();
					$soc->associationId = $model->associationId;
					$soc->data = CHtml::link($model->fileName,array('media/view','id'=>$model->id));
					if($soc->save()) {
						$this->redirect(array('profile/'.$model->associationId));
					} else {
						unlink('uploads/'.$name);
					}
					$this->redirect(array($model->associationType.'/'.$model->associationId));
					
				} else if($model->associationType=='bg' || $model->associationType=='bg-private') {

					$profile=CActiveRecord::model('ProfileChild')->findByPk(Yii::app()->user->getId());
					$profile->backgroundImg = $name;
					$profile->save();
					$this->redirect(array('profile/settings','id'=>Yii::app()->user->getId()));
				} else {
					$note=new ActionChild;
					$note->createDate = time();
					$note->dueDate = time();
					$note->completeDate = time();
					$note->complete='Yes';
					$note->visibility='1';
					$note->completedBy=Yii::app()->user->getName();
					$note->assignedTo='Anyone';
					$note->type='attachment';
					$note->associationId=$_POST['associationId'];
					$note->associationType=$_POST['type'];
					
					$association = $this->getAssociation($note->associationType,$note->associationId);
					if($association != null)
						$note->associationName = $association->name;

					$note->actionDescription = $model->fileName . ':' . $model->id;
					if($note->save()){
					} else {
						unlink('uploads/'.$name);
					}
					$this->redirect(array($model->associationType.'/'.$model->associationId));
				}
			}
		}
	}
Exemplo n.º 29
0
 /**
  * Fix email templates broken by the 5.1->5.2/5.3 media module changes.
  */
 public function actionConvertEmailTemplates()
 {
     $status = null;
     if (isset($_POST['yt0'])) {
         $docs = Docs::model()->findAllByAttributes(array('type' => 'email'));
         $converted = 0;
         foreach ($docs as $doc) {
             $changed = false;
             preg_match_all('|<img(.*?)src="(.*?)"(.*?)/?>|ism', $doc->text, $matches);
             $serverBasePath = Yii::app()->request->getServerName() . Yii::app()->baseUrl;
             foreach ($matches[2] as $filePath) {
                 if (strpos($filePath, $serverBasePath) !== false) {
                     $uploadPath = str_replace($serverBasePath, '', $filePath);
                     $pieces = explode('/', $uploadPath);
                     $fileName = $pieces[sizeof($pieces) - 1];
                     $mediaObj = Media::model()->findByAttributes(array('fileName' => $fileName));
                     if (isset($mediaObj)) {
                         $doc->text = preg_replace('|<img(.*?)src="' . preg_quote($filePath) . '"(.*?)/?>|ism', '<img\\1src="' . $mediaObj->getPublicUrl() . '"\\2/>', $doc->text);
                         $changed = true;
                     }
                 }
             }
             if ($changed) {
                 $doc->save();
                 $converted++;
             }
         }
         $status = $converted;
     }
     $this->render('convertEmailTemplates', array('status' => $status));
 }
Exemplo n.º 30
0
 public function init()
 {
     $this->models = Media::model()->last(Yii::app()->params['frontend']['itemsPerPage'])->findAll();
 }