示例#1
0
 private function saveAndDeleteMedia($type)
 {
     /** @var $model Media [ ] */
     $model = new Media();
     $mockRecord = $this->getMockRecord();
     $instruction = Deal::model()->findByPk($mockRecord['med_row']);
     $this->assertNotEmpty($instruction, "instruction not exist");
     $property = Property::model()->findByPk($instruction->dea_prop);
     $this->assertNotEmpty($property, "property not exist");
     $this->assertNotNull($property->addressId, "property has no address");
     $address = Address::model()->findByPk($property->addressId);
     $this->assertNotEmpty($address, " Address not exist");
     $model->setAttributes($this->getMockRecord());
     $model->file = $this->getMockCuploadedImage('image/jpeg', 1);
     if ($type == Media::TYPE_PHOTO) {
         $model->setCropFactor($this->getCropFactor());
     } elseif ($type == Media::TYPE_EPC || $type == Media::TYPE_FLOORPLAN) {
         $model->otherMedia = $type;
     }
     $this->assertTrue($model->validate(), "record not validated");
     $this->assertTrue($model->save(), "record not saved");
     foreach ($model->getImageSizes() as $imageSize) {
         $this->assertFileExists($model->getFullPath($imageSize), $imageSize . " does not exist");
     }
     $this->deleteMedia($model->med_id);
 }
示例#2
0
 public static function saveMedia($file, $parentId, $type, $className, $isMain)
 {
     if ($file['name']) {
         $media = new Media();
         $media->setParentId($parentId);
         $media->setType($type);
         $media->setClassName($className);
         $media->setPath($file['name']);
         //retrive file extention
         $fileNameArr = explode('.', $file['name']);
         $fileExt = end($fileNameArr);
         $media->setExt($fileExt);
         if ($isMain) {
             $media->setIsMain(1);
         }
         $media->save();
         //Save file
         if ($type == MediaPeer::IMAGE) {
             // resize image
             $image = new sfThumbnail(800, 800);
             $image->loadFile($file['tmp_name']);
             //$image->save(sfConfig::get('sf_upload_dir')."/$parentId/".$file['name'], 'image/jpeg');
             $image->save(sfConfig::get('sf_upload_dir') . "/" . $media->getId() . "." . $media->getExt());
             // create thunmbnail
             $imageTh = new sfThumbnail(80, 80);
             $imageTh->loadFile($file['tmp_name']);
             $imageTh->save(sfConfig::get('sf_upload_dir') . "/th_" . $media->getId() . "." . $media->getExt());
         }
     }
 }
示例#3
0
function getImage($img)
{
    try {
        if (strpos($img, 'http://') !== false) {
            $original_url = $img;
            $pos = strrpos($img, ".");
            $ext = substr($img, $pos + 1);
            $media = new Media();
            $media->save();
            $fileName = $media->getId() . "." . $ext;
            $basePath = sfConfig::get('sf_web_dir') . "/media/upload/";
            file_put_contents($basePath . $fileName, file_get_contents($img));
            $mime = explode(";", Media::mime_content_type($basePath . $fileName));
            $mime = $mime[0];
            $media->setFilename($fileName);
            $media->setFiletype($mime);
            $media->setFiledirpath($basePath);
            $media->save(null, $o);
            chmod($basePath . $fileName, 0777);
            $media->resizeImage(null, 450);
            $media->resizeImage(1, 150);
        } elseif (base64_decode($img)) {
            $ext = "jpg";
            $media = new Media();
            $media->save();
            $fileName = $media->getId() . "." . $ext;
            $basePath = sfConfig::get('sf_web_dir') . "/media/upload/";
            file_put_contents($basePath . $fileName, base64_decode($img));
            $mime = explode(";", Media::mime_content_type($basePath . $fileName));
            $mime = $mime[0];
            $media->setFilename($fileName);
            $media->setFiletype($mime);
            $media->setFiledirpath($basePath);
            $media->save(null, $o);
            chmod($basePath . $fileName, 0777);
            $media->resizeImage(null, 450);
            $media->resizeImage(1, 150);
        }
    } catch (Exception $e) {
        $media->delete();
        FileHelper::Log("CRON ERROR >>> Field : " . $k . " on item " . $o->getId() . "(" . $offer['originalid'] . ") is not a valid image. [" . $original_url . "]");
        echo_cms("CRON ERROR >>> Field : " . $k . " on item " . $o->getId() . "(" . $offer['originalid'] . ") is not a valid image. [" . $original_url . "]");
    }
}
示例#4
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Media();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Media'])) {
         $model->attributes = $_POST['Media'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 /**
  * Save uploaded file and add associated media object
  */
 public function saveAssociatedMedia($file)
 {
     if (!$file instanceof CUploadedFile) {
         return;
     }
     $fileAttribute = $this->fileAttribute;
     $media = new Media();
     $username = Yii::app()->user->getName();
     // file uploaded through form
     $tempName = $file->getTempName();
     $media->setAttributes(array('associationType' => $this->associationType, 'associationId' => $this->getAssociationId(), 'uploadedBy' => $username, 'createDate' => time(), 'lastUpdated' => time(), 'fileName' => preg_replace('/ /', '_', $file->getName()), 'mimetype' => $file->type), false);
     $media->resolveNameConflicts();
     if (!$media->save()) {
         throw new CException(implode(';', $media->getAllErrorMessages()));
     }
     if (!FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$media->fileName}")) {
         throw new CException();
     }
 }
 private function insertMedia($file)
 {
     /**
      * @var \yii\web\UploadedFile $file
      */
     $result = ['success' => false, 'message' => 'File could not be saved.'];
     if ($file->size > Yii::$app->params['maxUploadSize']) {
         $result['message'] = 'Max upload size limit reached';
     }
     $uploadTime = date("Y-m-W");
     $media = new Media();
     //TODO create your own model active record
     $media->filename = Inflector::slug(str_replace($file->extension, '', $file->name)) . '.' . $file->extension;
     $media->mimeType = $file->type;
     $media->byteSize = $file->size;
     $media->extension = $file->extension;
     $media->source = basename(\Yii::$app->params['uploadPath']) . '/' . $uploadTime . '/' . $media->filename;
     if (!is_file($media->source)) {
         //If saved upload the file
         $uploadPath = \Yii::$app->params['uploadPath'] . $uploadTime;
         if (!is_dir($uploadPath)) {
             mkdir($uploadPath, 0777, true);
         }
         if ($file->saveAs($uploadPath . '/' . $media->filename)) {
             //Save to media table
             if ($media->save(false)) {
                 $result['success'] = true;
                 $result['message'] = 'Upload Success';
                 $result['data'] = $media;
             } else {
                 $result['message'] = "Database record could not be saved.";
             }
         } else {
             $result['message'] = "File could not be saved.";
         }
     } else {
         $result['message'] = "File already exists.";
     }
     return $result;
 }
 public static function populate($con = null)
 {
     if ($con === null) {
         $con = Propel::getConnection(BookPeer::DATABASE_NAME);
     }
     $con->beginTransaction();
     // Add publisher records
     // ---------------------
     $scholastic = new Publisher();
     $scholastic->setName("Scholastic");
     // do not save, will do later to test cascade
     $morrow = new Publisher();
     $morrow->setName("William Morrow");
     $morrow->save($con);
     $morrow_id = $morrow->getId();
     $penguin = new Publisher();
     $penguin->setName("Penguin");
     $penguin->save();
     $penguin_id = $penguin->getId();
     $vintage = new Publisher();
     $vintage->setName("Vintage");
     $vintage->save($con);
     $vintage_id = $vintage->getId();
     $rowling = new Author();
     $rowling->setFirstName("J.K.");
     $rowling->setLastName("Rowling");
     // no save()
     $stephenson = new Author();
     $stephenson->setFirstName("Neal");
     $stephenson->setLastName("Stephenson");
     $stephenson->save($con);
     $stephenson_id = $stephenson->getId();
     $byron = new Author();
     $byron->setFirstName("George");
     $byron->setLastName("Byron");
     $byron->save($con);
     $byron_id = $byron->getId();
     $grass = new Author();
     $grass->setFirstName("Gunter");
     $grass->setLastName("Grass");
     $grass->save($con);
     $grass_id = $grass->getId();
     $phoenix = new Book();
     $phoenix->setTitle("Harry Potter and the Order of the Phoenix");
     $phoenix->setISBN("043935806X");
     $phoenix->setAuthor($rowling);
     $phoenix->setPublisher($scholastic);
     $phoenix->setPrice(10.99);
     $phoenix->save($con);
     $phoenix_id = $phoenix->getId();
     $qs = new Book();
     $qs->setISBN("0380977427");
     $qs->setTitle("Quicksilver");
     $qs->setPrice(11.99);
     $qs->setAuthor($stephenson);
     $qs->setPublisher($morrow);
     $qs->save($con);
     $qs_id = $qs->getId();
     $dj = new Book();
     $dj->setISBN("0140422161");
     $dj->setTitle("Don Juan");
     $dj->setPrice(12.99);
     $dj->setAuthor($byron);
     $dj->setPublisher($penguin);
     $dj->save($con);
     $dj_id = $dj->getId();
     $td = new Book();
     $td->setISBN("067972575X");
     $td->setTitle("The Tin Drum");
     $td->setPrice(13.99);
     $td->setAuthor($grass);
     $td->setPublisher($vintage);
     $td->save($con);
     $td_id = $td->getId();
     $r1 = new Review();
     $r1->setBook($phoenix);
     $r1->setReviewedBy("Washington Post");
     $r1->setRecommended(true);
     $r1->setReviewDate(time());
     $r1->save($con);
     $r1_id = $r1->getId();
     $r2 = new Review();
     $r2->setBook($phoenix);
     $r2->setReviewedBy("New York Times");
     $r2->setRecommended(false);
     $r2->setReviewDate(time());
     $r2->save($con);
     $r2_id = $r2->getId();
     $blob_path = _LOB_SAMPLE_FILE_PATH . '/tin_drum.gif';
     $clob_path = _LOB_SAMPLE_FILE_PATH . '/tin_drum.txt';
     $m1 = new Media();
     $m1->setBook($td);
     $m1->setCoverImage(file_get_contents($blob_path));
     // CLOB is broken in PDO OCI, see http://pecl.php.net/bugs/bug.php?id=7943
     if (get_class(Propel::getDB()) != "DBOracle") {
         $m1->setExcerpt(file_get_contents($clob_path));
     }
     $m1->save($con);
     // Add book list records
     // ---------------------
     // (this is for many-to-many tests)
     $blc1 = new BookClubList();
     $blc1->setGroupLeader("Crazyleggs");
     $blc1->setTheme("Happiness");
     $brel1 = new BookListRel();
     $brel1->setBook($phoenix);
     $brel2 = new BookListRel();
     $brel2->setBook($dj);
     $blc1->addBookListRel($brel1);
     $blc1->addBookListRel($brel2);
     $blc1->save();
     $bemp1 = new BookstoreEmployee();
     $bemp1->setName("John");
     $bemp1->setJobTitle("Manager");
     $bemp2 = new BookstoreEmployee();
     $bemp2->setName("Pieter");
     $bemp2->setJobTitle("Clerk");
     $bemp2->setSupervisor($bemp1);
     $bemp2->save($con);
     $bemp3 = new BookstoreCashier();
     $bemp3->setName("Tim");
     $bemp3->setJobTitle("Cashier");
     $bemp3->save($con);
     $role = new AcctAccessRole();
     $role->setName("Admin");
     $bempacct = new BookstoreEmployeeAccount();
     $bempacct->setBookstoreEmployee($bemp1);
     $bempacct->setAcctAccessRole($role);
     $bempacct->setLogin("john");
     $bempacct->setPassword("johnp4ss");
     $bempacct->save($con);
     // Add bookstores
     $store = new Bookstore();
     $store->setStoreName("Amazon");
     $store->setPopulationServed(5000000000);
     // world population
     $store->setTotalBooks(300);
     $store->save($con);
     $store = new Bookstore();
     $store->setStoreName("Local Store");
     $store->setPopulationServed(20);
     $store->setTotalBooks(500000);
     $store->save($con);
     $summary = new BookSummary();
     $summary->setSummarizedBook($phoenix);
     $summary->setSummary("Harry Potter does some amazing magic!");
     $summary->save();
     $con->commit();
 }
示例#8
0
 /**
  * Upload images via the media block.
  */
 public function postMediaUpload()
 {
     foreach ($_FILES["images"]["error"] as $key => $error) {
         if ($error == UPLOAD_ERR_OK) {
             $name = md5(time() . microtime() . $key . 'alan' . $key . 'joey');
             $extension = explode('.', $_FILES['images']['name'][$key]);
             $path = public_path() . '/uploads/media/' . $name . '.' . end($extension);
             move_uploaded_file($_FILES["images"]["tmp_name"][$key], $path);
             $media = new Media();
             $media->name = $name . '.' . end($extension);
             $media->filename = $path;
             $media->save();
         }
     }
 }
示例#9
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));
     }
 }
示例#10
0
 /**
  * Create a new theme record in the Media table, prevent duplicate filenames.
  * If theme cannot be saved, error message object is returned.
  */
 public function actionCreateTheme($themeAttributes)
 {
     $themeAttributesArr = CJSON::decode($themeAttributes);
     if (!in_array('themeName', array_keys($themeAttributesArr)) || !in_array('themeName', array_keys($themeAttributesArr))) {
         echo self::getThemeErrorMsg();
     }
     $theme = new Media();
     $theme->setScenario('themeCreate');
     $theme->fileName = $themeAttributesArr['themeName'];
     $theme->private = $themeAttributesArr['private'];
     $theme->associationType = "theme";
     $theme->uploadedBy = Yii::app()->user->name;
     $theme->description = $themeAttributes;
     if (!$theme->save()) {
         echo self::getThemeErrorMsg();
     } else {
         echo self::getThemeSuccessMsg(array('id' => $theme->id));
     }
 }
示例#11
0
文件: Media.php 项目: kotow/work
 public static function upload($fieldName, $to = "upload", $accept = array())
 {
     $request = sfContext::getInstance()->getRequest();
     if (strpos($fieldName, '/') === false) {
         $fileName = $request->getFileName($fieldName);
         $filePath = $request->getFilePath($fieldName);
         $error = $request->getFileValue($fieldName, "error");
         $real_file = false;
     } else {
         $fileName = $fieldName;
         $filePath = $fieldName;
         $error = 0;
         $real_file = true;
     }
     $fileType = self::mime_content_type($filePath);
     $fileTypes = explode(";", $fileType);
     $fileType = array_shift($fileTypes);
     if ($error = $request->getFileValue($fieldName, "error")) {
         switch ($error) {
             case 1:
                 $errorMsg = "UPLOAD_ERR_INI_SIZE";
                 break;
             case 2:
                 $errorMsg = "UPLOAD_ERR_FORM_SIZE";
                 break;
             case 3:
                 $errorMsg = "UPLOAD_ERR_PARTIAL";
                 break;
             case 4:
                 $errorMsg = "UPLOAD_ERR_NO_FILE";
                 break;
             case 5:
                 $errorMsg = "UPLOAD_ERR_NO_TMP_DIR";
                 break;
             case 6:
                 $errorMsg = "UPLOAD_ERR_CANT_WRITE";
                 break;
         }
     }
     if (!empty($accept)) {
         if (!empty($fileName) && !in_array($fileType, $accept)) {
             throw new Exception("UPLOAD_ERR_WRONG_FILE_TYPE");
         }
     }
     if ($request->getParameter('parent')) {
         $parent = Document::getDocumentInstance($request->getParameter('parent'));
     } else {
         $parent = Rootfolder::getRootfolderByModule('media');
     }
     $len = strlen(DIRECTORY_SEPARATOR);
     if (substr($to, -$len, $len) != DIRECTORY_SEPARATOR) {
         $to = $to . DIRECTORY_SEPARATOR;
     }
     //TODO
     $toPath = '/Applications/MAMP/trademark/httpdocs/media/upload/';
     //self::getMediaPath().$to;//
     $dirs = explode(DIRECTORY_SEPARATOR, $toPath);
     $thumbDir = '';
     foreach ($dirs as $dir) {
         $thumbDir .= $dir . DIRECTORY_SEPARATOR;
         try {
             if (!is_dir($thumbDir)) {
                 mkdir($thumbDir, 0777, true);
             }
         } catch (Exception $e) {
             throw new Exception("UPLOAD_ERR_CANT_CREATE_DIR");
         }
     }
     if (!$request->getParameter('id')) {
         if ($error) {
             throw new Exception($errorMsg);
         }
         $media = new Media();
         $media->save(null, $parent, false);
     } else {
         if ($error && $error != 4 && !empty($fileName)) {
             throw new Exception($errorMsg);
         }
         $media = Document::getDocumentInstance($request->getParameter('id'));
         if (!$media || get_class($media) != "Media") {
             $media = new Media();
             $media->save(null, $parent, false);
         } elseif ($error != 4) {
             if (file_exists($file = $media->getServerAbsoluteUrl())) {
                 @unlink($file);
             }
             if (file_exists($thumb = $media->getServerAbsoluteThumbUrl())) {
                 @unlink($thumb);
             }
         }
     }
     $ext = $media->getExtention($fileName);
     $extLen = strlen($ext);
     $saveFileName = $media->getId() . "." . $ext;
     if ($real_file) {
         @copy($fileName, $toPath . $saveFileName);
         @chmod($toPath . $saveFileName, 0777);
         @copy($fileName, $toPath . 'thumbs' . DIRECTORY_SEPARATOR . $saveFileName);
         @chmod($toPath . 'thumbs' . DIRECTORY_SEPARATOR . $saveFileName, 0777);
     } else {
         $request->moveFile($fieldName, $toPath . $saveFileName);
         @chmod($toPath . $saveFileName, 0777);
     }
     $media->setFilesize(filesize($toPath . $saveFileName));
     if (!$request->getParameter('attrLabel')) {
         $media->setLabel($fileName);
     } else {
         $media->setLabel($request->getParameter('attrLabel'));
     }
     $media->setDescription($request->getParameter('attrDescription'));
     if ($fileName != "") {
         $media->setFilename($saveFileName);
         $media->setFiledirpath(str_replace("\\", DIRECTORY_SEPARATOR, $to));
         $media->setFiletype($fileType);
     }
     $media->save(null, $parent);
     return $media;
 }
示例#12
0
 /**
  * Test #11. SYNCH get an existent object.
  * @depends testDataWipedBeforeTest
  * @depends testGetExistent
  */
 public function testSynchGet()
 {
     global $testTripId1;
     global $testMediaId1;
     global $synchAuthToken;
     // Create the object and set attributes
     $object = new Media($testTripId1, $testMediaId1);
     $object->setType('photo');
     $object->setCaption('Caption 1');
     $object->setTimestamp('2015-09-30 12:03:45');
     $object->setLocation('location');
     $object->setWidth('900');
     $object->setHeight('600');
     $object->setDeleted('Y');
     // Save the object and confirm a row is added to the database
     $this->assertTrue($object->save());
     $this->assertEquals(1, $this->countTestRows());
     $data = array('hash' => $object->getHash());
     $result = getApi('synchMedia.php', $data, $synchAuthToken);
     $this->assertEquals(RESPONSE_SUCCESS, $result['resultCode']);
     $this->assertTrue(isset($result['tripId']));
     $this->assertTrue(isset($result['mediaId']));
     $this->assertTrue(isset($result['created']));
     $this->assertTrue(isset($result['updated']));
     $this->assertTrue(isset($result['type']));
     $this->assertTrue(isset($result['caption']));
     $this->assertTrue(isset($result['timestamp']));
     $this->assertTrue(isset($result['location']));
     $this->assertTrue(isset($result['width']));
     $this->assertTrue(isset($result['height']));
     $this->assertTrue(isset($result['deleted']));
     $this->assertTrue(isset($result['hash']));
     $this->assertEquals($testTripId1, $result['tripId']);
     $this->assertEquals($testMediaId1, $result['mediaId']);
     $this->assertEquals($object->getCreated(), $result['created']);
     $this->assertEquals($object->getUpdated(), $result['updated']);
     $this->assertEquals('photo', $result['type']);
     $this->assertEquals('Caption 1', $result['caption']);
     $this->assertEquals('2015-09-30 12:03:45', $result['timestamp']);
     $this->assertEquals('location', $result['location']);
     $this->assertEquals('900', $result['width']);
     $this->assertEquals('600', $result['height']);
     $this->assertEquals('Y', $result['deleted']);
     $this->assertEquals($object->getHash(), $result['hash']);
 }
示例#13
0
} catch (Exception $e) {
    die("Error test date/time: " . $e->__toString());
}
// Handle BLOB/CLOB Columns
// ------------------------
try {
    print "\nTesting the BLOB/CLOB columns\n";
    print "-------------------------------\n\n";
    $blob_path = dirname(__FILE__) . '/etc/lob/tin_drum.gif';
    $blob2_path = dirname(__FILE__) . '/etc/lob/propel.gif';
    $clob_path = dirname(__FILE__) . '/etc/lob/tin_drum.txt';
    $m1 = new Media();
    $m1->setBook($phoenix);
    $m1->setCoverImage(file_get_contents($blob_path));
    $m1->setExcerpt(file_get_contents($clob_path));
    $m1->save();
    $m1_id = $m1->getId();
    print "Added Media collection [id = {$m1_id}].\n";
    print "Looking for just-created mediat by PK (={$m1_id}) .... ";
    try {
        $m1_lookup = MediaPeer::retrieveByPk($m1_id);
    } catch (Exception $e) {
        print "ERROR!\n";
        die("Error retrieving media by pk: " . $e->__toString());
    }
    if ($m1_lookup) {
        print "FOUND!\n";
    } else {
        print "NOT FOUND :(\n";
        die("Couldn't find just-created media item: media_id = {$m1_id}");
    }
示例#14
0
 public function save($runValidation = true, $attributes = null)
 {
     if ($this->photo) {
         // save related photo record
         $transaction = Yii::app()->db->beginTransaction();
         try {
             // save the event
             $ret = parent::save($runValidation, $attributes);
             if (!$ret) {
                 throw new CException(implode(';', $this->getAllErrorMessages()));
             }
             // add media record for file
             $media = new Media();
             $media->setAttributes(array('fileName' => $this->photo->getName(), 'mimetype' => $this->photo->type), false);
             $media->resolveNameConflicts();
             if (!$media->save()) {
                 throw new CException(implode(';', $media->getAllErrorMessages()));
             }
             // save the file
             $tempName = $this->photo->getTempName();
             $username = Yii::app()->user->getName();
             if (!FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$media->fileName}")) {
                 throw new CException();
             }
             // relate file to event
             $join = new RelationshipsJoin('insert', 'x2_events_to_media');
             $join->eventsId = $this->id;
             $join->mediaId = $media->id;
             if (!$join->save()) {
                 throw new CException(implode(';', $join->getAllErrorMessages()));
             }
             $transaction->commit();
             return $ret;
         } catch (CException $e) {
             $transaction->rollback();
             return false;
         }
     } else {
         return parent::save($runValidation, $attributes);
     }
 }
示例#15
0
 /**
  * Extra test
  * Make sure that a long text is saved in the media, one that has
  * at least more than 256 characters.
  * @depends testSaveEmptyObject
  * @depends testSetAttributes
  */
 public function testLongText()
 {
     global $testTripId1, $testMediaId1;
     $longText = "This is a long text. This is a very long text. This is a ver, very long text. In fact, this text will just go on and on and on, for up to 400 characters. So when we set and retrieve this text, we will know for sure that the system supports these long texts. Of course, if this fails, we won't know any such thing for sure. Would that be to happen, we will have to go and spend some quality debugging time with the system.";
     $object = new Media($testTripId1, $testMediaId1);
     $object->setCaption($longText);
     $this->assertTrue($object->save());
     $object = new Media($testTripId1, $testMediaId1);
     $this->assertEquals($longText, $object->getCaption());
 }
示例#16
0
 public function save($validate = true)
 {
     $this->logger->clear();
     //	validation
     $valid = !$validate || $this->validate();
     //	get a user_id, either by adding new user or fetching id of existing
     if ($valid) {
         $user = new User(null, $this->db);
         $user->email = $this->email;
         $user->name = $this->username;
         if (!is_null($user->email) && !empty($user->email)) {
             $user->loadFromEmail();
         } else {
             if (!is_null($user->name) && !empty($user->name)) {
                 $user->loadFromName();
             }
         }
         if ($this->isImport) {
             $user->implied = 1;
         }
         if ($user->id) {
             $this->logger->log("user found...");
         } else {
             $user->ip = $_SERVER['REMOTE_ADDR'];
         }
         $success = $user->save();
         $this->user_id = $user->id;
         if (is_null($this->user_id)) {
             $valid = false;
         }
     }
     if ($valid && isset($this->imageUpload) && !empty($this->imageUpload["name"]) && $this->imageUpload["error"] == 0) {
         $this->logger->log("saving image...");
         $image = new Media(null, $this->db);
         $image->name = time();
         $image->mime_type = $this->imageUpload['type'];
         $image->tempFile = $this->imageUpload;
         if ($image->validate()) {
             if ($image->save()) {
                 $this->logger->log("image saved...");
             } else {
                 $this->status = $image->errorMessage;
                 $valid = false;
                 $this->logger->log("error saving image...");
             }
         } else {
             $this->status = $image->errorMessage;
             $valid = false;
         }
     }
     if ($valid && isset($this->audioUpload) && !empty($this->audioUpload["name"]) && $this->audioUpload["error"] == 0) {
         $this->logger->log("saving audio...");
         $audio = new Media(null, $this->db);
         $audio->name = time();
         $audio->mime_type = $this->audioUpload['type'];
         $audio->tempFile = $this->audioUpload;
         if ($audio->validate()) {
             if ($audio->save()) {
                 $this->logger->log("audio saved...");
             } else {
                 $this->status = $audio->errorMessage;
                 $valid = false;
                 $this->logger->log("error saving audio...");
             }
         } else {
             $this->status = $audio->errorMessage;
             $valid = false;
             $this->logger->log("error validating audio...");
         }
     }
     $get_location = curl_init();
     curl_setopt($get_location, CURLOPT_URL, "http://freegeoip.net/json/" . $_SERVER['REMOTE_ADDR']);
     curl_setopt($get_location, CURLOPT_RETURNTRANSFER, 1);
     $location = curl_exec($get_location);
     $location = json_decode($location);
     //	import dream
     if ($valid) {
         $date = DateTime::createFromFormat($this->dateFormat, $this->date, new DateTimeZone($this->timezone));
         $this->occur_date = $date->format('Y-m-d');
         if ($location) {
             $this->city = $location->city;
             $this->country = $location->country_name;
             $this->latitude = $location->latitude;
             $this->longitude = $location->longitude;
         } else {
             $this->latitude = "0";
             $this->longitude = "0";
         }
         $success = parent::save();
         if ($success) {
             $this->status = "Dream added!";
         } else {
             if (isset($this->errorMessage)) {
                 $this->status = $this->errorMessage;
             } else {
                 $this->status = "Error updating dream";
             }
             $valid = false;
         }
     }
     if (isset($image)) {
         if (!is_null($this->id) && !empty($this->id)) {
             $image->dream_id = $this->id;
             $image->save();
         } else {
             $image->delete();
         }
         $this->logger->log($image->logger->log);
     }
     if (isset($audio)) {
         if (!is_null($this->id) && !empty($this->id)) {
             $audio->dream_id = $this->id;
             $audio->save();
         } else {
             $audio->delete();
         }
         $this->logger->log($audio->logger->log);
     }
     $tags = array();
     //	add dream tags
     if ($valid && $this->useAlchemy) {
         $kb = strlen($this->description) / 1024;
         if ($kb <= 150) {
             $alchemy = new AlchemyAPI($this->alchemyApiKey);
             $params = array();
             $params['maxRetrieve'] = 20;
             $params['keywordExtractMode'] = 'strict';
             $params['sentiment'] = 1;
             $params['showSourceText'] = 0;
             try {
                 $result = $alchemy->keywords('text', $this->description, $params);
                 $this->logger->log("alchemy " . $result['status'] . ", " . (isset($result['keywords']) ? count($result['keywords']) : 0) . " keywords, " . $this->description);
             } catch (Exception $e) {
                 $this->logger->log("alchemy, " . $result['status'] . ", " . $result['statusInfo']);
             }
             if (isset($result) && $result['status'] == "OK") {
                 foreach ($result['keywords'] as $keyword) {
                     $tag = stripslashes($keyword['text']);
                     $tag = preg_replace("/^\\W|\\W\$|\\./", "", $tag);
                     $tag = strtolower(trim($tag));
                     $tag = $this->db->real_escape_string($tag);
                     //	get tag_id
                     $sql = "SELECT id FROM `tags` WHERE tag='" . $tag . "'";
                     $result2 = $this->db->query($sql);
                     if ($this->db->affected_rows > 0) {
                         $tag_row = $result2->fetch_assoc();
                         $tag_id = $tag_row['id'];
                     } else {
                         $sql = "INSERT INTO `tags` (tag,alchemy) VALUES ('" . $tag . "','1')";
                         $this->db->query($sql);
                         $tag_id = $this->db->insert_id;
                     }
                     if ($tag_id) {
                         $sentiment = $keyword['sentiment'];
                         $sql = "INSERT INTO `dream_tags` (dream_id,tag_id,sentiment_type,sentiment_score) VALUES ('" . $this->id . "','" . $tag_id . "','" . $sentiment['type'] . "','" . (isset($sentiment['score']) ? $sentiment['score'] : 0) . "')";
                         $this->db->query($sql);
                     }
                     $tags[] = $tag;
                 }
             }
         } else {
             $this->logger->log("Dream " . $this->id . " to big to process" . $kb);
         }
     }
     if ($valid && $this->postToTumblr && $this->tumblrPostEmail != null) {
         $to = $this->tumblrPostEmail;
         $subject = isset($this->title) ? $this->title : "untitled";
         $body = $this->description;
         $body .= "\n\nDreamt on " . $this->date . " by a " . $this->age . " year old " . ($this->gender == "male" ? "man" : "woman") . " in " . $location->city;
         $body .= "\n\nhttp://artefactsofthecollectiveunconscious.net/browse.php?did=" . $this->id;
         $tagline = '';
         foreach ($tags as $tag) {
             $tagline .= "#" . $tag . " ";
         }
         $body .= "\n\n" . $tagline;
         mail($to, $subject, $body);
     }
     if ($valid) {
         foreach ($this->feelings as $feeling_id) {
             if ($feeling_id) {
                 $sql = "INSERT INTO `dream_feelings` (dream_id,feeling_id) VALUES ('" . $this->id . "','" . $feeling_id . "')";
                 $result = $this->db->query($sql);
             }
         }
     }
     if ($valid) {
         $this->init();
     }
     return $valid;
 }
示例#17
0
 /**
  * Creates a new media object via an ajax upload
  *
  */
 public function actionAjaxUpload()
 {
     $fileUrl = '';
     try {
         if (Yii::app()->user->isGuest) {
             throw new Exception('You are not logged in.');
         }
         if (!isset($_FILES['upload'], $_GET['CKEditorFuncNum'])) {
             //,$_GET['Media']
             throw new Exception('Invalid request.');
         }
         $upload = CUploadedFile::getInstanceByName('upload');
         if ($upload == null) {
             throw new Exception('Invalid file.');
         }
         $fileName = $upload->getName();
         $fileName = str_replace(' ', '_', $fileName);
         $userFolder = Yii::app()->user->name;
         // place uploaded files in a folder named with the username of the user that uploaded the file
         $userFolderPath = 'uploads/media/' . $userFolder;
         // if user folder doesn't exit, try to create it
         if (!(file_exists($userFolderPath) && is_dir($userFolderPath))) {
             if (!@mkdir('uploads/media/' . $userFolder, 0777, true)) {
                 // make dir with edit permission
                 throw new Exception('Error creating user folder.');
                 // ERROR: Couldn't create user folder
                 // var_dump($userFolder);
                 // exit();
             }
         }
         if (!$upload->saveAs($userFolderPath . DIRECTORY_SEPARATOR . $fileName)) {
             throw new Exception('Error saving file');
         }
         // save media info
         $model = new Media();
         $model->fileName = $fileName;
         $model->createDate = time();
         $model->lastUpdated = time();
         $model->uploadedBy = Yii::app()->user->name;
         $model->associationType = 'none';
         // $model->associationType = $_GET['Media']['associationType'];
         // $model->associationId = $_GET['Media']['associationId'];
         $model->private = true;
         //$_GET['Media']['private'];
         // if($_POST['GET']['description'])
         // $model->description = $_POST['Media']['description'];
         if (!$model->save()) {
             throw new Exception('Error saving Media entry');
         }
         $fileUrl = $model->getFullUrl();
     } catch (Exception $e) {
         echo '<html><body><script type="text/javascript">', 'window.parent.CKEDITOR.tools.callFunction(', json_encode($_GET['CKEditorFuncNum']), ',"","', $e->getMessage(), '");', '</script></body></html>';
         return;
     }
     echo '<html><body><script type="text/javascript">', 'window.parent.CKEDITOR.tools.callFunction(', json_encode($_GET['CKEditorFuncNum']), ',"', json_encode($fileUrl), '","");', '</script></body></html>';
 }
示例#18
0
 public function convertToMedia(array $attributes = array())
 {
     $username = Yii::app()->user->getName();
     $name = $this->name;
     $tempFilename = 'uploads/protected/media/temp/' . $this->folder . '/' . $this->name;
     if (FileUtil::ccopy($tempFilename, "uploads/protected/media/{$username}/{$name}")) {
         $model = new Media();
         $model->name = $model->fileName = $name;
         $model->uploadedBy = $username;
         $model->createDate = time();
         $model->lastUpdated = time();
         $model->resolveType();
         $model->resolveSize();
         $model->setAttributes($attributes, false);
         if ($model->save()) {
             return $model;
         }
     }
     return false;
 }
示例#19
0
 /**
  * @param $post
  * @param $feeds
  * @param $user_id
  */
 private function _save_attachment($post, $feeds, $user_id)
 {
     $category_slug = $feeds['attachment_type'];
     $media = new Media();
     $media->path = __DIR__ . '/../../public/uploads/' . $user_id . '/' . $feeds['image_name'];
     if ($category_slug == 'videos') {
         $media->type = 'video';
     } else {
         $media->type = 'image';
     }
     $media->user_id = $user_id;
     $media->save();
     $post->save($media, 'media');
 }
示例#20
0
 /**
  * 简单上传一个文件,然后用标准JSON格式返回文件的地址,不记录数据库数据
  * @param Request $request
  * @param Response $response
  */
 public function upfile(Request $request, Response $response)
 {
     if ($request->has_files()) {
         $upfile = $request->files('upfile');
         $dbsave = $request->get('dbsave', 0);
         $isplayer = $request->get('isplayer', 0);
         $extpart = strtolower(strrchr($upfile['name'], '.'));
         $fileext = substr($extpart, 1);
         $filetype = 'attach';
         if ('swf' == $fileext) {
             $filetype = 'flash';
         } elseif (in_array($fileext, array('jpg', 'jpeg', 'png', 'gif'))) {
             $filetype = 'pic';
         } elseif ('apk' == $fileext) {
             $filetype = 'android';
         } elseif ('ipa' == $fileext) {
             $filetype = 'ios';
         } elseif ('xap' == $fileext || 'cab' == $fileext) {
             $filetype = 'wp';
         } elseif (in_array($fileext, array('mp3'))) {
             $filetype = 'audio';
         }
         if ($isplayer) {
             $filetype = 'player';
         }
         //~ create directory
         $targetfilecode = date('d_His') . '_' . randchar();
         $targetfile = $targetfilecode . $extpart;
         $targetdir = ltrim($this->_uproot_dir, '/') . "{$filetype}/" . date('Ym') . '/';
         if ($isplayer) {
             $targetdir .= 'original/';
         }
         if (!is_dir($targetdir)) {
             mkdirs($targetdir, 0777, TRUE);
         }
         //~ move upload file to target dir
         $filepath = $targetdir . $targetfile;
         move_uploaded_file($upfile['tmp_name'], $filepath);
         chmod($filepath, 0644);
         if (file_exists($filepath)) {
             $mid = 0;
             $width = 0;
             $height = 0;
             $size = filesize($filepath);
             if ($filetype == 'pic') {
                 list($width, $height, $type, $attr) = getimagesize($filepath);
             }
             $filepath_site = C('env.contextpath', '/') . $filepath;
             //要补上网站的根路径
             if ($dbsave) {
                 $data = ['mtype' => $filetype, 'filesize' => $size, 'path' => $filepath_site];
                 $mid = Media::save($data);
             }
             if ($isplayer) {
                 $rt = Upload_Model::makeImgThumb($filepath_site);
                 if (is_numeric($rt)) {
                     $response->sendJSON(['flag' => 'ERR', 'msg' => 'make thumb fail']);
                 } else {
                     $mid = Upload_Model::savePlayerGallery(0, $rt);
                 }
             }
             $response->sendJSON(['flag' => 'OK', 'msg' => 'upload file success', 'mid' => $mid, 'path' => $filepath_site, 'type' => $filetype, 'width' => $width, 'height' => $height, 'size' => $size]);
         }
         $response->sendJSON(['flag' => 'ERR', 'msg' => 'upload file error']);
     }
     $response->sendJSON(['flag' => 'ERR_NOFILES', 'msg' => 'no files upload']);
 }
示例#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'));
	}
示例#22
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));
     }
 }
 public function testLobSetting_WriteMode()
 {
     $blob_path = $this->getLobFile('tin_drum.gif');
     $blob2_path = $this->getLobFile('propel.gif');
     $clob_path = $this->getLobFile('tin_drum.txt');
     $book = BookPeer::doSelectOne(new Criteria());
     $m1 = new Media();
     $m1->setBook($book);
     $m1->setCoverImage(file_get_contents($blob_path));
     $m1->setExcerpt(file_get_contents($clob_path));
     $m1->save();
     MediaPeer::clearInstancePool();
     // make sure we have the latest from the db:
     $m2 = MediaPeer::retrieveByPK($m1->getId());
     // now attempt to assign a temporary stream, opened in 'w' mode, to the db
     $stream = fopen("php://memory", 'w');
     fwrite($stream, file_get_contents($blob2_path));
     $m2->setCoverImage($stream);
     $m2->save();
     fclose($stream);
     $m2->reload();
     $this->assertEquals(md5(file_get_contents($blob2_path)), md5(stream_get_contents($m2->getCoverImage())), "Expected contents to match when setting stream w/ 'w' mode");
     $stream2 = fopen("php://memory", 'w+');
     fwrite($stream2, file_get_contents($blob_path));
     rewind($stream2);
     $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($stream2)), "Expecting setup to be correct");
     $m2->setCoverImage($stream2);
     $m2->save();
     $m2->reload();
     $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($m2->getCoverImage())), "Expected contents to match when setting stream w/ 'w+' mode");
 }
 public function testScenarioUsingQuery()
 {
     // Add publisher records
     // ---------------------
     try {
         $scholastic = new Publisher();
         $scholastic->setName("Scholastic");
         // do not save, will do later to test cascade
         $morrow = new Publisher();
         $morrow->setName("William Morrow");
         $morrow->save();
         $morrow_id = $morrow->getId();
         $penguin = new Publisher();
         $penguin->setName("Penguin");
         $penguin->save();
         $penguin_id = $penguin->getId();
         $vintage = new Publisher();
         $vintage->setName("Vintage");
         $vintage->save();
         $vintage_id = $vintage->getId();
         $this->assertTrue(true, 'Save Publisher records');
     } catch (Exception $e) {
         $this->fail('Save publisher records');
     }
     // Add author records
     // ------------------
     try {
         $rowling = new Author();
         $rowling->setFirstName("J.K.");
         $rowling->setLastName("Rowling");
         // do not save, will do later to test cascade
         $stephenson = new Author();
         $stephenson->setFirstName("Neal");
         $stephenson->setLastName("Stephenson");
         $stephenson->save();
         $stephenson_id = $stephenson->getId();
         $byron = new Author();
         $byron->setFirstName("George");
         $byron->setLastName("Byron");
         $byron->save();
         $byron_id = $byron->getId();
         $grass = new Author();
         $grass->setFirstName("Gunter");
         $grass->setLastName("Grass");
         $grass->save();
         $grass_id = $grass->getId();
         $this->assertTrue(true, 'Save Author records');
     } catch (Exception $e) {
         $this->fail('Save Author records');
     }
     // Add book records
     // ----------------
     try {
         $phoenix = new Book();
         $phoenix->setTitle("Harry Potter and the Order of the Phoenix");
         $phoenix->setISBN("043935806X");
         $phoenix->setAuthor($rowling);
         $phoenix->setPublisher($scholastic);
         $phoenix->save();
         $phoenix_id = $phoenix->getId();
         $this->assertFalse($rowling->isNew(), 'saving book also saves related author');
         $this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher');
         $qs = new Book();
         $qs->setISBN("0380977427");
         $qs->setTitle("Quicksilver");
         $qs->setAuthor($stephenson);
         $qs->setPublisher($morrow);
         $qs->save();
         $qs_id = $qs->getId();
         $dj = new Book();
         $dj->setISBN("0140422161");
         $dj->setTitle("Don Juan");
         $dj->setAuthor($byron);
         $dj->setPublisher($penguin);
         $dj->save();
         $dj_id = $qs->getId();
         $td = new Book();
         $td->setISBN("067972575X");
         $td->setTitle("The Tin Drum");
         $td->setAuthor($grass);
         $td->setPublisher($vintage);
         $td->save();
         $td_id = $td->getId();
         $this->assertTrue(true, 'Save Book records');
     } catch (Exception $e) {
         $this->fail('Save Author records');
     }
     // Add review records
     // ------------------
     try {
         $r1 = new Review();
         $r1->setBook($phoenix);
         $r1->setReviewedBy("Washington Post");
         $r1->setRecommended(true);
         $r1->setReviewDate(time());
         $r1->save();
         $r1_id = $r1->getId();
         $r2 = new Review();
         $r2->setBook($phoenix);
         $r2->setReviewedBy("New York Times");
         $r2->setRecommended(false);
         $r2->setReviewDate(time());
         $r2->save();
         $r2_id = $r2->getId();
         $this->assertTrue(true, 'Save Review records');
     } catch (Exception $e) {
         $this->fail('Save Review records');
     }
     // Perform a "complex" search
     // --------------------------
     $results = BookQuery::create()->filterByTitle('Harry%')->find();
     $this->assertEquals(1, count($results));
     $results = BookQuery::create()->where('Book.ISBN IN ?', array("0380977427", "0140422161"))->find();
     $this->assertEquals(2, count($results));
     // Perform a "limit" search
     // ------------------------
     $results = BookQuery::create()->limit(2)->offset(1)->orderByTitle()->find();
     $this->assertEquals(2, count($results));
     // we ordered on book title, so we expect to get
     $this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle());
     $this->assertEquals("Quicksilver", $results[1]->getTitle());
     // Perform a lookup & update!
     // --------------------------
     // Updating just-created book title
     // First finding book by PK (=$qs_id) ....
     $qs_lookup = BookQuery::create()->findPk($qs_id);
     $this->assertNotNull($qs_lookup, 'just-created book can be found by pk');
     $new_title = "Quicksilver (" . crc32(uniqid(rand())) . ")";
     // Attempting to update found object
     $qs_lookup->setTitle($new_title);
     $qs_lookup->save();
     // Making sure object was correctly updated: ";
     $qs_lookup2 = BookQuery::create()->findPk($qs_id);
     $this->assertEquals($new_title, $qs_lookup2->getTitle());
     // Test some basic DATE / TIME stuff
     // ---------------------------------
     // that's the control timestamp.
     $control = strtotime('2004-02-29 00:00:00');
     // should be two in the db
     $r = ReviewQuery::create()->findOne();
     $r_id = $r->getId();
     $r->setReviewDate($control);
     $r->save();
     $r2 = ReviewQuery::create()->findPk($r_id);
     $this->assertEquals(new Datetime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime');
     $this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp');
     $this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter');
     // Handle BLOB/CLOB Columns
     // ------------------------
     $blob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif';
     $blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif';
     $clob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.txt';
     $m1 = new Media();
     $m1->setBook($phoenix);
     $m1->setCoverImage(file_get_contents($blob_path));
     $m1->setExcerpt(file_get_contents($clob_path));
     $m1->save();
     $m1_id = $m1->getId();
     $m1_lookup = MediaQuery::create()->findPk($m1_id);
     $this->assertNotNull($m1_lookup, 'Can find just-created media item');
     $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($m1_lookup->getCoverImage())), 'BLOB was correctly updated');
     $this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated');
     // now update the BLOB column and save it & check the results
     $m1_lookup->setCoverImage(file_get_contents($blob2_path));
     $m1_lookup->save();
     $m2_lookup = MediaQuery::create()->findPk($m1_id);
     $this->assertNotNull($m2_lookup, 'Can find just-created media item');
     $this->assertEquals(md5(file_get_contents($blob2_path)), md5(stream_get_contents($m2_lookup->getCoverImage())), 'BLOB was correctly overwritten');
     // Test Validators
     // ---------------
     require_once 'tools/helpers/bookstore/validator/ISBNValidator.php';
     $bk1 = new Book();
     $bk1->setTitle("12345");
     // min length is 10
     $ret = $bk1->validate();
     $this->assertFalse($ret, 'validation failed');
     $failures = $bk1->getValidationFailures();
     $this->assertEquals(1, count($failures), '1 validation message was returned');
     $el = array_shift($failures);
     $this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned');
     $bk2 = new Book();
     $bk2->setTitle("Don Juan");
     $ret = $bk2->validate();
     $this->assertFalse($ret, 'validation failed');
     $failures = $bk2->getValidationFailures();
     $this->assertEquals(1, count($failures), '1 validation message was returned');
     $el = array_shift($failures);
     $this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned');
     //Now trying some more complex validation.
     $auth1 = new Author();
     $auth1->setFirstName("Hans");
     // last name required; will fail
     $bk1->setAuthor($auth1);
     $rev1 = new Review();
     $rev1->setReviewDate("08/09/2001");
     // will fail: reviewed_by column required
     $bk1->addReview($rev1);
     $ret2 = $bk1->validate();
     $this->assertFalse($ret2, 'validation failed');
     $failures2 = $bk1->getValidationFailures();
     $this->assertEquals(3, count($failures2), '3 validation messages were returned');
     $expectedKeys = array(AuthorPeer::LAST_NAME, BookPeer::TITLE, ReviewPeer::REVIEWED_BY);
     $this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed');
     $bk2 = new Book();
     $bk2->setTitle("12345678901");
     // passes
     $auth2 = new Author();
     $auth2->setLastName("Blah");
     //passes
     $auth2->setEmail("*****@*****.**");
     //passes
     $auth2->setAge(50);
     //passes
     $bk2->setAuthor($auth2);
     $rev2 = new Review();
     $rev2->setReviewedBy("Me!");
     // passes
     $rev2->setStatus("new");
     // passes
     $bk2->addReview($rev2);
     $ret3 = $bk2->validate();
     $this->assertTrue($ret3, 'complex validation can pass');
     // Testing doCount() functionality
     // -------------------------------
     // old way
     $c = new Criteria();
     $records = BookPeer::doSelect($c);
     $count = BookPeer::doCount($c);
     $this->assertEquals($count, count($records), 'correct number of results');
     // new way
     $count = BookQuery::create()->count();
     $this->assertEquals($count, count($records), 'correct number of results');
     // Test many-to-many relationships
     // ---------------
     // init book club list 1 with 2 books
     $blc1 = new BookClubList();
     $blc1->setGroupLeader("Crazyleggs");
     $blc1->setTheme("Happiness");
     $brel1 = new BookListRel();
     $brel1->setBook($phoenix);
     $brel2 = new BookListRel();
     $brel2->setBook($dj);
     $blc1->addBookListRel($brel1);
     $blc1->addBookListRel($brel2);
     $blc1->save();
     $this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved');
     // init book club list 2 with 1 book
     $blc2 = new BookClubList();
     $blc2->setGroupLeader("John Foo");
     $blc2->setTheme("Default");
     $brel3 = new BookListRel();
     $brel3->setBook($phoenix);
     $blc2->addBookListRel($brel3);
     $blc2->save();
     $this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved');
     // re-fetch books and lists from db to be sure that nothing is cached
     $crit = new Criteria();
     $crit->add(BookPeer::ID, $phoenix->getId());
     $phoenix = BookPeer::doSelectOne($crit);
     $this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db");
     $crit = new Criteria();
     $crit->add(BookClubListPeer::ID, $blc1->getId());
     $blc1 = BookClubListPeer::doSelectOne($crit);
     $this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db');
     $crit = new Criteria();
     $crit->add(BookClubListPeer::ID, $blc2->getId());
     $blc2 = BookClubListPeer::doSelectOne($crit);
     $this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db');
     $relCount = $phoenix->countBookListRels();
     $this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels");
     $relCount = $blc1->countBookListRels();
     $this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels');
     $relCount = $blc2->countBookListRels();
     $this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel');
     // Cleanup (tests DELETE)
     // ----------------------
     // Removing books that were just created
     // First finding book by PK (=$phoenix_id) ....
     $hp = BookQuery::create()->findPk($phoenix_id);
     $this->assertNotNull($hp, 'Could find just-created book');
     // Attempting to delete [multi-table] by found pk
     $c = new Criteria();
     $c->add(BookPeer::ID, $hp->getId());
     // The only way for cascading to work currently
     // is to specify the author_id and publisher_id (i.e. the fkeys
     // have to be in the criteria).
     $c->add(AuthorPeer::ID, $hp->getAuthor()->getId());
     $c->add(PublisherPeer::ID, $hp->getPublisher()->getId());
     $c->setSingleRecord(true);
     BookPeer::doDelete($c);
     // Checking to make sure correct records were removed.
     $this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table');
     $this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table');
     $this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table');
     // Attempting to delete books by complex criteria
     BookQuery::create()->filterByISBN("043935806X")->orWhere('Book.ISBN = ?', "0380977427")->orWhere('Book.ISBN = ?', "0140422161")->delete();
     // Attempting to delete book [id = $td_id]
     $td->delete();
     // Attempting to delete authors
     AuthorQuery::create()->filterById($stephenson_id)->delete();
     AuthorQuery::create()->filterById($byron_id)->delete();
     $grass->delete();
     // Attempting to delete publishers
     PublisherQuery::create()->filterById($morrow_id)->delete();
     PublisherQuery::create()->filterById($penguin_id)->delete();
     $vintage->delete();
     // These have to be deleted manually also since we have onDelete
     // set to SETNULL in the foreign keys in book. Is this correct?
     $rowling->delete();
     $scholastic->delete();
     $blc1->delete();
     $blc2->delete();
     $this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table');
     $this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table');
     $this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table');
     $this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table');
     $this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table');
     $this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table');
     $this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table');
 }
示例#25
0
            $object = new Media($tripId, $mediaId);
            if (isset($data['type'])) {
                $object->setType($data['type']);
            }
            if (isset($data['caption'])) {
                $object->setCaption($data['caption']);
            }
            if (isset($data['timestamp'])) {
                $object->setTimestamp($data['timestamp']);
            }
            if (isset($data['location'])) {
                $object->setLocation($data['location']);
            }
            if (isset($data['width'])) {
                $object->setWidth($data['width']);
            }
            if (isset($data['height'])) {
                $object->setHeight($data['height']);
            }
            if (isset($data['deleted'])) {
                $object->setDeleted($data['deleted']);
            }
            if ($object->save()) {
                $response = successResponse();
            } else {
                $response = errorResponse(RESPONSE_INTERNAL_ERROR);
            }
        }
    }
}
echo json_encode($response);
示例#26
0
 public function postSavemediafiles($title_id = null)
 {
     if (Input::hasFile('upload_media_file')) {
         $destination_path = public_path() . Config::get('nbc.imageRootLocalPath');
         // i.e.  c:\xamp\htdocs\laravel\www\public/media/shared/assets/images/,
         $relative_base_url = Config::get('nbc.imageRootLocalPath');
         //this should be:  /media/shared/assets/images/, for purposes of rendering the uploaded image in realtime after choosing file from operating system
         //            error_log ("dest: $destination_path, rel: $relative_base_url");
         $mediafile = Input::hasFile('upload_media_file');
         $input = array('image' => $mediafile);
         $rules = array('upload_media_file' => 'image');
         $validator = Validator::make($input, $rules);
         if ($validator->fails()) {
             return Response::json(['success' => false, 'errors' => $validator->getMessageBag()->toArray()]);
         } else {
             // Set media table field values
             // ----------------------------
             $selected_index = Input::get("media_select");
             switch ($selected_index) {
                 case 1:
                     $mediatype_id = 5;
                     break;
                 case 2:
                     $mediatype_id = 1;
                     break;
                 case 3:
                     $mediatype_id = 3;
                     break;
             }
             $filename = Input::file('upload_media_file')->getClientOriginalName();
             try {
                 $destination_filename = md5(microtime()) . "_" . str_replace(" ", "-", $filename);
                 Input::file('upload_media_file')->move($destination_path, $destination_filename);
             } catch (Exception $e) {
                 //                     error_log( $e->getMessage() );
                 return Response::json(['success' => false, 'message' => $e->getMessage()]);
             }
             return Response::json(['success' => true, 'mediatype' => $mediatype_id, 'file' => asset($relative_base_url . $destination_filename), 'abs_path' => $destination_path . $destination_filename, 'filename' => $destination_filename, 'orig_filename' => $filename]);
         }
     } else {
         if (Input::hasFile('upload_video_file')) {
             $videofile_path = "/media/shared/assets/videos/";
             $destination_path = public_path() . $videofile_path;
             $relative_base_url = $videofile_path;
             $filename = Input::file('upload_video_file')->getClientOriginalName();
             try {
                 $destination_filename = md5(microtime()) . "_" . str_replace(" ", "-", $filename);
                 Input::file('upload_video_file')->move($destination_path, $destination_filename);
                 $media_rec = new Media();
                 $media_rec->mediatype_id = 6;
                 $media_rec->file = $destination_filename;
                 $media_rec->status_id = 5;
                 $media_rec->description = "Promo Video";
                 $media_rec->save();
                 $media_id = $media_rec->id;
                 //                $media_title_rec = new MediaTitle;
                 //                $media_title_rec->media_id = $media_id;
                 //                $media_title_rec->title_id = Input::get('title_id');
                 //                $media_title_rec->save();
             } catch (Exception $e) {
                 //                 error_log( $e->getMessage() );
                 return Response::json(['success' => false, 'message' => $e->getMessage()]);
             }
             return Response::json(['success' => true, 'mediatype' => 6, 'file' => asset($relative_base_url . $destination_filename), 'abs_path' => $destination_path . $destination_filename, 'filename' => $destination_filename, 'orig_filename' => $filename, 'id' => $media_id]);
         }
     }
 }
示例#27
0
    $page->content = Input::get('content');
    $page->publish = Input::get('publish');
    $page->save();
    return Redirect::to('admin/pages');
}), 'POST /admin/newmedia' => array('before' => 'auth', function () {
    $imagename = time() . Input::file('image.name');
    File::upload('image', PUBLIC_PATH . 'img/' . $imagename);
    $newimage = PUBLIC_PATH . 'img/' . $imagename;
    $image = new Imagick($newimage);
    $image->scaleImage(400, 0);
    $image->writeImage(PUBLIC_PATH . 'img/medium_' . $imagename);
    $image->resizeImage(80, 80, Imagick::FILTER_LANCZOS, 1, TRUE);
    $image->writeImage(PUBLIC_PATH . 'img/thumb_' . $imagename);
    $image->destroy();
    $media = new Media();
    $media->filename = $imagename;
    $media->caption = Input::get('caption');
    $media->meta = Input::get('meta');
    $media->save();
    return Redirect::to('admin/media');
}), 'POST /admin/newuser' => array('before' => 'auth', function () {
    $rules = array('firstname' => 'required|max:140', 'lastname' => 'required|max:140', 'email' => 'required|max:50|unique:users', 'role' => 'required', 'password' => 'required|max:50|between:6,16|confirmed');
    $validator = Validator::make(Input::get(), $rules);
    if (!$validator->valid()) {
        return Redirect::to('admin/newuser')->with('errors', $validator->errors)->with_input('except', array('password', 'password_confirmation'));
    }
    $user = new User();
    $user->fill(array('firstname' => Input::get('firstname'), 'lastname' => Input::get('lastname'), 'email' => Input::get('email'), 'role' => Input::get('role'), 'password' => Hash::make(Input::get('password'))));
    $user->save();
    return Redirect::to('admin');
}));
示例#28
0
 /**
  * Reverts the logo back to X2Engine.
  */
 public function actionToggleDefaultLogo()
 {
     $adminProf = Yii::app()->params->adminProfile;
     $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/protected/logos/' . $name;
         if ($logo->save()) {
         }
     } else {
         if ($logo->fileName != 'uploads/protected/logos/yourlogohere.png') {
             $logo->delete();
         }
     }
     $this->redirect(array('index'));
 }
示例#29
0
 /**
  * Upload a custom logo
  *
  * This method allows for the admin to upload their own logo to go in place of
  * the X2Engine logo in the top left corner of the software.
  */
 public function actionUploadLogo()
 {
     Yii::import('application.models.formModels.UploadLogoFormModel');
     $formModel = new UploadLogoFormModel();
     if (isset($_POST['UploadLogoFormModel']) && isset($_FILES['UploadLogoFormModel'])) {
         $adminProf = Yii::app()->params->adminProfile;
         $formModel->setAttributes($_POST['UploadLogoFormModel']);
         $formModel->menuLogoUpload = CUploadedFile::getInstance($formModel, 'menuLogoUpload');
         $uploaded = false;
         if ($formModel->validate()) {
             foreach (array('menuLogoUpload') as $upload) {
                 if ($formModel->{$upload}) {
                     $fileName = 'uploads/protected/logos/' . $formModel->{$upload}->getName();
                     if ($formModel->{$upload}->saveAs($fileName)) {
                         $uploaded = true;
                         if ($upload === 'menuLogoUpload') {
                             $associationType = 'logo';
                         } else {
                             $associationType = 'loginLogo';
                         }
                         $oldLogo = Media::model()->findByAttributes(array('associationId' => $adminProf->id, 'associationType' => $associationType));
                         $logo = new Media();
                         $logo->associationType = $associationType;
                         $logo->associationId = $adminProf->id;
                         $logo->name = $fileName;
                         $logo->fileName = $fileName;
                         if ($logo->save() && $oldLogo) {
                             $oldLogo->delete();
                         }
                     } else {
                         $formModel->addError($upload, Yii::t('admin', 'File could not be uploaded'));
                     }
                 }
             }
         }
         if (!$formModel->hasErrors() && $uploaded) {
             Yii::app()->user->setFlash('success', Yii::t('admin', 'Logo uploaded.'));
             $this->redirect('uploadLogo');
         }
     }
     $this->render('uploadLogo', array('formModel' => $formModel));
 }
示例#30
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));
				}
			}
		}
	}