Esempio n. 1
0
 /**
  * Retrieve all the tags.
  */
 function index_get()
 {
     header('Access-Control-Allow-Origin: *');
     $lat = $this->get('lat');
     $lon = $this->get('lon');
     $radiusInMeters = $this->get('radius');
     $timespanInMinutes = $this->get('timespanInMinutes');
     $tagModel = new TagModel($this->db);
     if ($lat != null && $lon != null) {
         if ($radiusInMeters == null) {
             $radiusInMeters = self::LOCATION_RADIUS_METERS;
         }
         $tags = $tagModel->getTagsAroundLocation($lat, $lon, $radiusInMeters);
     } else {
         if ($timespanInMinutes == null) {
             $timespanInMinutes = self::TIMESPAN_DEFAULT_DAYS * 24 * 60;
         }
         $fromDate = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s")) - $timespanInMinutes * 60);
         $tags = $tagModel->getTags($fromDate);
     }
     $tagsJson = array();
     foreach ($tags as $tag) {
         $tagsJson[] = $tag->serialize();
     }
     if (empty($tagsJson)) {
         $this->response(error('No tags found.', 404), 404);
     } else {
         $this->response($tagsJson);
     }
 }
Esempio n. 2
0
 function insert_tags()
 {
     $tags = new \TagModel();
     $newTags = array('CSS', 'HTML', 'JavaScript', 'Techniques', 'Typography', 'Inspiration', 'Business', 'User Experience', 'E-Commerce', 'Design Pattern');
     foreach ($newTags as $record) {
         $tags->title = $record;
         $tags->save();
         $tags->reset();
     }
     $this->test->message($this->getTime() . " imported 10 Tags ");
 }
Esempio n. 3
0
 /**
  * Get instance
  * @return unknown_type
  */
 public static function getInstance()
 {
     if (!self::$_instance instanceof self) {
         self::$_instance = new self();
     }
     return self::$_instance;
 }
 public function GetData()
 {
     $TagQuery = Gdn::SQL();
     $this->AutoContext();
     $TagCacheKey = "TagModule-{$this->ParentType}-{$this->ParentID}";
     switch ($this->ParentType) {
         case 'Discussion':
             $Tags = TagModel::instance()->getDiscussionTags($this->ParentID, false);
             break;
         case 'Category':
             $TagQuery->Join('TagDiscussion td', 't.TagID = td.TagID')->Select('COUNT(DISTINCT td.TagID)', '', 'NumTags')->Where('td.CategoryID', $this->ParentID)->GroupBy('td.TagID')->Cache($TagCacheKey, 'get', array(Gdn_Cache::FEATURE_EXPIRY => 120));
             break;
         case 'Global':
             $TagCacheKey = 'TagModule-Global';
             $TagQuery->Where('t.CountDiscussions >', 0, FALSE)->Cache($TagCacheKey, 'get', array(Gdn_Cache::FEATURE_EXPIRY => 120));
             if ($this->CategorySearch) {
                 $TagQuery->Where('t.CategoryID', '-1');
             }
             break;
     }
     if (isset($Tags)) {
         $this->_TagData = new Gdn_DataSet($Tags, DATASET_TYPE_ARRAY);
     } else {
         $this->_TagData = $TagQuery->Select('t.*')->From('Tag t')->OrderBy('t.CountDiscussions', 'desc')->Limit(25)->Get();
     }
     $this->_TagData->DatasetType(DATASET_TYPE_ARRAY);
 }
Esempio n. 5
0
 public function Matching($param)
 {
     // Matching Checking
     if (parent::AlreadyMatingProcess($param)) {
         return parent::CreateMatchingProcess($param);
     } else {
         parent::RemoveMatchingProcess($param);
     }
 }
 public function showAction()
 {
     $tag = TagModel::getInstance()->fetchEntryByCleanName($this->_getParam('name'));
     if (null === $tag) {
         return $this->_forward('notfound', 'error');
     }
     $taggedStreamModel = TaggedStreamModel::getInstance();
     $entries = $this->_paginateResult($taggedStreamModel->fetchStreamsByTag($tag), $this->_getParam('page', 1));
     $this->view->tag = $tag;
     $this->view->entries = $entries;
 }
Esempio n. 7
0
 /**
  * Read tags from database
  * @return string
  */
 protected function readTags()
 {
     $arrTags = array();
     $tags = \TagModel::findByIdAndTable($this->activeRecord->id, $this->table);
     if ($tags) {
         while ($tags->next()) {
             array_push($arrTags, $tags->tag);
         }
     }
     return count($arrTags) ? implode(",", $arrTags) : '';
 }
Esempio n. 8
0
 private function searchTag()
 {
     if ($_GET['type'] == 3) {
         $this->_model->inputkeyword = $_GET['inputkeyword'];
         parent::page($this->_model->searchTagContentTotal(), ARTICLE_SIZE);
         $_object = $this->_model->searchTagContent();
         Tool::subStr($_object, 'info', 120, 'utf-8');
         Tool::subStr($_object, 'title', 35, 'utf-8');
         if ($_object) {
             foreach ($_object as $_value) {
                 if (empty($_value->thumbnail)) {
                     $_value->thumbnail = 'images/none.jpg';
                 }
             }
         }
         $_tag = new TagModel();
         $_tag->tagname = $this->_model->inputkeyword;
         $_tag->getOneTag() ? $_tag->addTagCount() : $_tag->addTag();
         $this->_tpl->assign('SearchContent', $_object);
     }
 }
Esempio n. 9
0
 /**
  * 添加标签
  * 开放权限
  * @method POST_infoAction
  * @param  integer         $id [description]
  * @author NewFuture
  */
 public function POST_infoAction($id = 0)
 {
     $uid = $this->auth();
     if (Input::post('sid', $sid, 'int') && TagModel::where('id', $id)->inc('count')) {
         $Hastag = new Model('hastag');
         $hastag = ['tag_id' => $id, 'sha_id' => $sid];
         try {
             $Hastag->insert($hastag);
             $this->response(1, '添加成功');
         } catch (Exception $e) {
             TagModel::where('id', $id)->inc('count', '-1');
             $this->response(0, '添加出错');
         }
     } else {
         $this->response(0, '分享或者标签有误');
     }
 }
Esempio n. 10
0
 public function prepTags($data, $field)
 {
     $fieldData = array();
     if (!empty($data)) {
         $settings = $field->getFieldType()->getSettings();
         // Get tag group id
         $source = $settings->getAttribute('source');
         list($type, $groupId) = explode(':', $source);
         $tags = ArrayHelper::stringToArray($data);
         foreach ($tags as $tag) {
             $tagArray = array();
             if (!empty($tag)) {
                 // Find existing tag
                 $criteria = craft()->elements->getCriteria(ElementType::Tag);
                 $criteria->title = DbHelper::escapeParam($tag);
                 $criteria->limit = 1;
                 $criteria->groupId = $groupId;
                 if (!$criteria->total()) {
                     // Create tag if one doesn't already exist
                     $newtag = new TagModel();
                     $newtag->getContent()->title = $tag;
                     $newtag->groupId = $groupId;
                     // Save tag
                     if (craft()->tags->saveTag($newtag)) {
                         $tagArray = array($newtag->id);
                     }
                 } else {
                     $tagArray = $criteria->ids();
                 }
             }
             // Add tags to data array
             $fieldData = array_merge($fieldData, $tagArray);
         }
     }
     return $fieldData;
 }
Esempio n. 11
0
 /**
  * Saves a tag.
  *
  * @param TagModel $tag
  *
  * @throws Exception|\Exception
  * @return bool
  */
 public function saveTag(TagModel $tag)
 {
     $isNewTag = !$tag->id;
     // Tag data
     if (!$isNewTag) {
         $tagRecord = TagRecord::model()->findById($tag->id);
         if (!$tagRecord) {
             throw new Exception(Craft::t('No tag exists with the ID “{id}”.', array('id' => $tag->id)));
         }
     } else {
         $tagRecord = new TagRecord();
     }
     $tagRecord->groupId = $tag->groupId;
     $tagRecord->validate();
     $tag->addErrors($tagRecord->getErrors());
     if ($tag->hasErrors()) {
         return false;
     }
     $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
     try {
         // Fire an 'onBeforeSaveTag' event
         $event = new Event($this, array('tag' => $tag, 'isNewTag' => $isNewTag));
         $this->onBeforeSaveTag($event);
         // Is the event giving us the go-ahead?
         if ($event->performAction) {
             $success = craft()->elements->saveElement($tag, false);
             // If it didn't work, rollback the transaction in case something changed in onBeforeSaveTag
             if (!$success) {
                 if ($transaction !== null) {
                     $transaction->rollback();
                 }
                 return false;
             }
             // Now that we have an element ID, save it on the other stuff
             if ($isNewTag) {
                 $tagRecord->id = $tag->id;
             }
             $tagRecord->save(false);
         } else {
             $success = false;
         }
         // Commit the transaction regardless of whether we saved the tag, in case something changed
         // in onBeforeSaveTag
         if ($transaction !== null) {
             $transaction->commit();
         }
     } catch (\Exception $e) {
         if ($transaction !== null) {
             $transaction->rollback();
         }
         throw $e;
     }
     if ($success) {
         // Fire an 'onSaveTag' event
         $this->onSaveTag(new Event($this, array('tag' => $tag, 'isNewTag' => $isNewTag)));
         if ($this->hasEventHandler('onSaveTagContent')) {
             // Fire an 'onSaveTagContent' event (deprecated)
             $this->onSaveTagContent(new Event($this, array('tag' => $tag)));
         }
     }
     return $success;
 }
Esempio n. 12
0
 /**
  *
  *
  * @param $Filename
  * @param $Get
  * @return bool|string
  */
 public function filenameRedirect($Filename, $Get)
 {
     trace(['Filename' => $Filename, 'Get' => $Get], 'Testing');
     $Filename = strtolower($Filename);
     array_change_key_case($Get);
     if (!isset(self::$Files[$Filename])) {
         return false;
     }
     $Row = self::$Files[$Filename];
     if (is_callable($Row)) {
         // Use a callback to determine the translation.
         $Row = call_user_func_array($Row, [&$Get]);
     }
     trace($Get, 'New Get');
     // Translate all of the get parameters into new parameters.
     $Vars = array();
     foreach ($Get as $Key => $Value) {
         if (!isset($Row[$Key])) {
             continue;
         }
         $Opts = (array) $Row[$Key];
         if (isset($Opts['Filter'])) {
             // Call the filter function to change the value.
             $R = call_user_func($Opts['Filter'], $Value, $Opts[0]);
             if (is_array($R)) {
                 if (isset($R[0])) {
                     // The filter can change the column name too.
                     $Opts[0] = $R[0];
                     $Value = $R[1];
                 } else {
                     // The filter can return return other variables too.
                     $Vars = array_merge($Vars, $R);
                     $Value = null;
                 }
             } else {
                 $Value = $R;
             }
         }
         if ($Value !== null) {
             $Vars[$Opts[0]] = $Value;
         }
     }
     trace($Vars, 'Translated Arguments');
     // Now let's see what kind of record we have.
     // We'll check the various primary keys in order of importance.
     $Result = false;
     if (isset($Vars['CommentID'])) {
         trace("Looking up comment {$Vars['CommentID']}.");
         $CommentModel = new CommentModel();
         // If a legacy slug is provided (assigned during a merge), attempt to lookup the comment using it
         if (isset($Get['legacy']) && Gdn::Structure()->Table('Comment')->ColumnExists('ForeignID')) {
             $Comment = $CommentModel->GetWhere(['ForeignID' => $Get['legacy'] . '-' . $Vars['CommentID']])->FirstRow();
         } else {
             $Comment = $CommentModel->GetID($Vars['CommentID']);
         }
         if ($Comment) {
             $Result = CommentUrl($Comment, '//');
         }
     } elseif (isset($Vars['DiscussionID'])) {
         trace("Looking up discussion {$Vars['DiscussionID']}.");
         $DiscussionModel = new DiscussionModel();
         $DiscussionID = $Vars['DiscussionID'];
         $Discussion = false;
         if (is_numeric($DiscussionID)) {
             // If a legacy slug is provided (assigned during a merge), attempt to lookup the discussion using it
             if (isset($Get['legacy']) && Gdn::Structure()->Table('Discussion')->ColumnExists('ForeignID')) {
                 $Discussion = $DiscussionModel->GetWhere(['ForeignID' => $Get['legacy'] . '-' . $DiscussionID])->FirstRow();
             } else {
                 $Discussion = $DiscussionModel->GetID($Vars['DiscussionID']);
             }
         } else {
             // This is a slug style discussion ID. Let's see if there is a UrlCode column in the discussion table.
             $DiscussionModel->DefineSchema();
             if ($DiscussionModel->Schema->FieldExists('Discussion', 'UrlCode')) {
                 $Discussion = $DiscussionModel->GetWhere(['UrlCode' => $DiscussionID])->FirstRow();
             }
         }
         if ($Discussion) {
             $Result = DiscussionUrl($Discussion, self::pageNumber($Vars, 'Vanilla.Comments.PerPage'), '//');
         }
     } elseif (isset($Vars['UserID'])) {
         trace("Looking up user {$Vars['UserID']}.");
         $User = Gdn::UserModel()->GetID($Vars['UserID']);
         if ($User) {
             $Result = Url(UserUrl($User), '//');
         }
     } elseif (isset($Vars['TagID'])) {
         $Tag = TagModel::instance()->GetID($Vars['TagID']);
         if ($Tag) {
             $Result = TagUrl($Tag, self::pageNumber($Vars, 'Vanilla.Discussions.PerPage'), '//');
         }
     } elseif (isset($Vars['CategoryID'])) {
         trace("Looking up category {$Vars['CategoryID']}.");
         // If a legacy slug is provided (assigned during a merge), attempt to lookup the category ID based on it
         if (isset($Get['legacy']) && Gdn::Structure()->Table('Category')->ColumnExists('ForeignID')) {
             $CategoryModel = new CategoryModel();
             $Category = $CategoryModel->GetWhere(['ForeignID' => $Get['legacy'] . '-' . $Vars['CategoryID']])->FirstRow();
         } else {
             $Category = CategoryModel::Categories($Vars['CategoryID']);
         }
         if ($Category) {
             $Result = categoryUrl($Category, self::pageNumber($Vars, 'Vanilla.Discussions.PerPage'), '//');
         }
     } elseif (isset($Vars['CategoryCode'])) {
         trace("Looking up category {$Vars['CategoryCode']}.");
         $category = CategoryModel::instance()->getByCode($Vars['CategoryCode']);
         if ($category) {
             $pageNumber = self::pageNumber($Vars, 'Vanilla.Discussions.PerPage');
             if ($pageNumber > 1) {
                 $pageParam = '?Page=' . $pageNumber;
             } else {
                 $pageParam = null;
             }
             $Result = categoryUrl($category, '', '//') . $pageParam;
         }
     }
     return $Result;
 }
Esempio n. 13
0
 function run($db, $type)
 {
     $test = new \Test();
     // clear existing data
     \AuthorModel::setdown();
     \TagModel::setdown();
     \NewsModel::setdown();
     \ProfileModel::setdown();
     // setup models
     \AuthorModel::setup();
     \TagModel::setup();
     \NewsModel::setup();
     \ProfileModel::setup();
     // setup Author
     ///////////////////////////////////
     $author_id = array();
     $author = new \AuthorModel();
     $ac = $author::resolveConfiguration();
     $author_pk = is_int(strpos($type, 'sql')) ? $ac['primary'] : '_id';
     $author->name = 'Johnny English';
     $author->save();
     $author_id[] = $author->_id;
     $author->reset();
     $author->name = 'Ridley Scott';
     $author->save();
     $author_id[] = $author->_id;
     $author->reset();
     $author->name = 'James T. Kirk';
     $author->save();
     $author_id[] = $author->_id;
     $author->reset();
     $allauthors = $author->find()->castAll();
     $allauthors = $this->getResult($allauthors);
     $test->expect(json_encode($allauthors) == '[{"name":"Johnny English"},{"name":"Ridley Scott"},{"name":"James T. Kirk"}]', $type . ': all AuthorModel items created');
     // setup Tags
     ///////////////////////////////////
     $tag_id = array();
     $tag = new \TagModel();
     $tc = $tag::resolveConfiguration();
     $tag_pk = is_int(strpos($type, 'sql')) ? $tc['primary'] : '_id';
     $tag->title = 'Web Design';
     $tag->save();
     $tag_id[] = $tag->_id;
     $tag->reset();
     $tag->title = 'Responsive';
     $tag->save();
     $tag_id[] = $tag->_id;
     $tag->reset();
     $tag->title = 'Usability';
     $tag->save();
     $tag_id[] = $tag->_id;
     $tag->reset();
     $allTags = $this->getResult($tag->find());
     $test->expect(json_encode($allTags) == '[{"title":"Web Design"},{"title":"Responsive"},{"title":"Usability"}]', $type . ': all TagModel items created');
     // setup News
     ///////////////////////////////////
     $news_id = array();
     $news = new \NewsModel();
     $nc = $news::resolveConfiguration();
     $news_pk = is_int(strpos($type, 'sql')) ? $nc['primary'] : '_id';
     $news->title = 'Responsive Images';
     $news->text = 'Lorem Ipsun';
     $news->save();
     $news_id[] = $news->_id;
     $news->reset();
     $news->title = 'CSS3 Showcase';
     $news->text = 'News Text 2';
     $news->save();
     $news_id[] = $news->_id;
     $news->reset();
     $news->title = 'Touchable Interfaces';
     $news->text = 'Lorem Foo';
     $news->save();
     $news_id[] = $news->_id;
     $news->reset();
     $allnews = $this->getResult($news->find(null, array('order' => 'title')));
     $test->expect(count($allnews) == 3 && $allnews[0]['title'] == 'CSS3 Showcase' && $allnews[1]['title'] == 'Responsive Images' && $allnews[2]['title'] == 'Touchable Interfaces', $type . ': all NewsModel items created');
     // belongs-to author relation
     ///////////////////////////////////
     $author->load();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $news->author = $author;
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $test->expect($news->author->name == 'Johnny English', $type . ': belongs-to-one: author relation created');
     $news->author = NULL;
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $test->expect(empty($news->author), $type . ': belongs-to-one: author relation released');
     $news->author = $author->_id;
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $test->expect($news->author->name == 'Johnny English', $type . ': belongs-to-one: relation created by raw id');
     // belongs-to-many tag relation
     ///////////////////////////////////
     $tag1 = new \TagModel();
     $tag1->load(array($tag_pk . ' = ?', $tag_id[0]));
     $tag2 = new \TagModel();
     $tag2->load(array($tag_pk . ' = ?', $tag_id[1]));
     $news->tags = array($tag1, $tag2);
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $test->expect($news->tags[0]->title == 'Web Design' && $news->tags[1]->title == 'Responsive', $type . ': belongs-to-many: relations created with array of mapper objects');
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[1]));
     $news->tags = array($tag_id[1], $tag_id[2]);
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[1]));
     $test->expect(count($news->tags) == 2 && $news->tags[0]->title == 'Responsive' && $news->tags[1]->title == 'Usability', $type . ': belongs-to-many: relations created with array of IDs');
     $news->tags = null;
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[1]));
     $test->expect(empty($news->tags), $type . ': belongs-to-many: relations released');
     $tag->reset();
     $news->load(array($news_pk . ' = ?', $news_id[1]));
     $news->tags = $tag->load(array($tag_pk . ' != ?', $tag_id[0]));
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[1]));
     $test->expect($news->tags[0]->title == 'Responsive' && $news->tags[1]->title == 'Usability', $type . ': belongs-to-many: relations created with hydrated mapper');
     $news->reset();
     $tag->reset();
     $news->load(array($news_pk . ' = ?', $news_id[2]));
     $news->tags = $tag_id[0] . ';' . $tag_id[2];
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[2]));
     $test->expect($news->tags[0]->title == 'Web Design' && $news->tags[1]->title == 'Usability', $type . ': belongs-to-many: relations created with split-able string');
     $test->expect(is_object($news->tags) && $news->tags instanceof \DB\CortexCollection, $type . ': belongs-to-many: result is collection');
     // has-one relation
     ///////////////////////////////////
     $profile = new ProfileModel();
     $pc = $profile::resolveConfiguration();
     $profile_pk = is_int(strpos($type, 'sql')) ? $pc['primary'] : '_id';
     $profile->message = 'Hello World';
     $profile->author = $author->load(array($author_pk . ' = ?', $author_id[0]));
     $profile->save();
     $profile_id = $profile->_id;
     $profile->reset();
     $author->reset();
     $author->load(array($author_pk . ' = ?', $author_id[0]));
     $profile->load(array($profile_pk . ' = ?', $profile_id));
     $test->expect($author->profile->message == 'Hello World' && $profile->author->name == "Johnny English", $type . ': has-one: relation assigned');
     $profile->reset();
     $profile->message = 'I\'m feeling lucky';
     $profile->image = 'lolcat.jpg';
     $author->reset();
     $author->load(array($author_pk . ' = ?', $author_id[1]));
     $author->profile = $profile;
     $author->save();
     $profile->reset();
     $author->reset();
     $author->load(array($author_pk . ' = ?', $author_id[1]));
     $test->expect($author->profile->message == 'I\'m feeling lucky', $type . ': has-one: inverse relation');
     // has-many relation
     ///////////////////////////////////
     $author->load(array($author_pk . ' = ?', $author_id[0]));
     $result = $this->getResult($author->news);
     $test->expect($result[0]['title'] == "Responsive Images" && $result[0]['tags'][0]['title'] == 'Web Design' && $result[0]['tags'][1]['title'] == 'Responsive', $type . ': has-many inverse relation');
     // many to many relation
     ///////////////////////////////////
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $news->tags2 = array($tag_id[0], $tag_id[1]);
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $test->expect($news->tags2[0]['title'] == 'Web Design' && $news->tags2[1]['title'] == 'Responsive', $type . ': many-to-many relation created');
     $test->expect(is_object($news->tags2) && $news->tags2 instanceof \DB\CortexCollection, $type . ': many-to-many: result is collection');
     $tag3 = $tag->load(array($tag_pk . ' = ?', $tag_id[2]));
     $news->tags2[] = $tag3;
     $news->save();
     $a = count($news->tags2);
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $test->expect(count($news->tags2) == 3 && $a == 3, $type . ': many-to-many relation added implicitly');
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $news->tags2 = NULL;
     $news->save();
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $test->expect(is_null($news->tags2), $type . ': many-to-many relation released');
     $news->reset();
     $news->title = 'Can it run Crysis?';
     $news->text = 'XOXO';
     $news->tags2 = array($tag_id[0]);
     $news->save();
     $news_id[] = $news->_id;
     $news->reset();
     $news->load(array($news_pk . ' = ?', $news_id[3]));
     $a = count($news->tags2);
     $tag1 = $tag->find(array($tag_pk . ' = ?', $tag_id[0]));
     $b = count($tag1[0]->news);
     $c = $tag1[0]->news[0]->title == 'Can it run Crysis?';
     $news->erase();
     $tag1 = $tag->find(array($tag_pk . ' = ?', $tag_id[0]));
     $d = count($tag1[0]->news);
     $test->expect($a == 1 && $b == 1 && $c && $d == 0, $type . ': many-to-many relation cleaned by erase cascade');
     $news->load(array($news_pk . ' = ?', $news_id[0]));
     $all = $news->find();
     $test->expect($all[1]->tags2 === NULL && $all[2]->author === NULL, $type . ': empty relations are NULL');
     $arr = $news->cast();
     $test->expect(is_array($arr['tags']), $type . ': collection becomes array in casted model');
     if ($type == 'mongo') {
         $test->expect(is_string($arr['_id']), $type . ': id becomes string in casted model');
     }
     ///////////////////////////////////
     return $test->results();
 }
Esempio n. 14
0
 /**
  * updateInfo
  *
  * Update info of internalflight
  *
  * @param stdClass $para para for update info of internalflight
  */
 public function updateInfo($para)
 {
     try {
         if ($this->validateUpdateInfo($para)) {
             $internalflightBO = $this->get($para->post_id);
             if ($internalflightBO != NULL) {
                 if (isset($para->post_title) && $internalflightBO->post_title != $para->post_title) {
                     $internalflightBO->post_title = $para->post_title;
                 }
                 if (isset($para->post_content) && $internalflightBO->post_content != $para->post_content) {
                     $internalflightBO->post_content = $para->post_content;
                 }
                 if (isset($para->post_name) && $internalflightBO->post_name != $para->post_name) {
                     $internalflightBO->post_name = $para->post_name;
                 }
                 $internalflightBO->post_modified = date("Y-m-d H:i:s");
                 $internalflightBO->post_modified_gmt = gmdate("Y-m-d H:i:s");
                 $this->db->beginTransaction();
                 if (isset($para->image)) {
                     Model::autoloadModel("image");
                     $imageModel = new ImageModel($this->db);
                     $imageModel->is_create_thumb = true;
                     $imageModel->is_medium = true;
                     $image_array_id = $imageModel->uploadImages("image");
                     if (!is_null($image_array_id) && is_array($image_array_id) && sizeof($image_array_id) != 0) {
                         $image_id = $image_array_id[0];
                         $image_id_old = $internalflightBO->image_id;
                     } else {
                         $_SESSION["fb_error"][] = ERROR_UPLOAD_IMAGE_FAILED;
                         $this->db->rollBack();
                         return FALSE;
                     }
                 }
                 if ($this->update($internalflightBO)) {
                     $guid = CONTEXT_PATH_INTERNALFLIGHT_VIEW . $para->post_id . "/" . $internalflightBO->post_name . "/";
                     if (isset($internalflightBO->guid) && $internalflightBO->guid != $guid || !isset($internalflightBO->guid)) {
                         $internalflightBO->guid = $guid;
                         if (!$this->updateGuid($para->post_id, $guid)) {
                             $this->db->rollBack();
                             if (isset($imageModel) && isset($image_id)) {
                                 $imageModel->delete($image_id);
                             }
                             $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                             return FALSE;
                         }
                     }
                     if (isset($image_id)) {
                         if (!isset($internalflightBO->image_id)) {
                             $internalflightBO->image_id = $image_id;
                             if ($this->addMetaInfoToDatabase($para->post_id, "image_id", $internalflightBO->image_id) == NULL) {
                                 $this->db->rollBack();
                                 if (isset($imageModel) && isset($image_id)) {
                                     $imageModel->delete($image_id);
                                 }
                                 $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                 return FALSE;
                             }
                         } else {
                             if ($internalflightBO->image_id != $image_id) {
                                 $internalflightBO->image_id = $image_id;
                                 if (!$this->updateMetaInfoToDatabase($para->post_id, "image_id", $internalflightBO->image_id)) {
                                     $this->db->rollBack();
                                     if (isset($imageModel) && isset($image_id)) {
                                         $imageModel->delete($image_id);
                                     }
                                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                     return FALSE;
                                 }
                             }
                         }
                     }
                     if (isset($para->current_rating)) {
                         if (!isset($internalflightBO->current_rating)) {
                             $internalflightBO->current_rating = $para->current_rating;
                             if ($this->addMetaInfoToDatabase($para->post_id, "current_rating", $internalflightBO->current_rating) == NULL) {
                                 $this->db->rollBack();
                                 if (isset($imageModel) && isset($current_rating)) {
                                     $imageModel->delete($current_rating);
                                 }
                                 $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                 return FALSE;
                             }
                         } else {
                             if ($internalflightBO->current_rating != $para->current_rating) {
                                 $internalflightBO->current_rating = $para->current_rating;
                                 if (!$this->updateMetaInfoToDatabase($para->post_id, "current_rating", $internalflightBO->current_rating)) {
                                     $this->db->rollBack();
                                     if (isset($imageModel) && isset($current_rating)) {
                                         $imageModel->delete($current_rating);
                                     }
                                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                     return FALSE;
                                 }
                             }
                         }
                     }
                     if (isset($para->vote_times)) {
                         if (!isset($internalflightBO->vote_times)) {
                             $internalflightBO->vote_times = $para->vote_times;
                             if ($this->addMetaInfoToDatabase($para->post_id, "vote_times", $internalflightBO->vote_times) == NULL) {
                                 $this->db->rollBack();
                                 if (isset($imageModel) && isset($vote_times)) {
                                     $imageModel->delete($vote_times);
                                 }
                                 $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                 return FALSE;
                             }
                         } else {
                             if ($internalflightBO->vote_times != $para->vote_times) {
                                 $internalflightBO->vote_times = $para->vote_times;
                                 if (!$this->updateMetaInfoToDatabase($para->post_id, "vote_times", $internalflightBO->vote_times)) {
                                     $this->db->rollBack();
                                     if (isset($imageModel) && isset($vote_times)) {
                                         $imageModel->delete($vote_times);
                                     }
                                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                     return FALSE;
                                 }
                             }
                         }
                     }
                     if (isset($para->city_id)) {
                         if (!isset($internalflightBO->city_id)) {
                             $internalflightBO->city_id = $para->city_id;
                             if ($this->addMetaInfoToDatabase($para->post_id, "city_id", $internalflightBO->city_id) == NULL) {
                                 $this->db->rollBack();
                                 if (isset($imageModel) && isset($city_id)) {
                                     $imageModel->delete($city_id);
                                 }
                                 $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                 return FALSE;
                             }
                         } else {
                             if ($internalflightBO->city_id != $para->city_id) {
                                 $internalflightBO->city_id = $para->city_id;
                                 if (!$this->updateMetaInfoToDatabase($para->post_id, "city_id", $internalflightBO->city_id)) {
                                     $this->db->rollBack();
                                     if (isset($imageModel) && isset($city_id)) {
                                         $imageModel->delete($city_id);
                                     }
                                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                     return FALSE;
                                 }
                             }
                         }
                     }
                     if (isset($para->country_id)) {
                         if (!isset($internalflightBO->country_id)) {
                             $internalflightBO->country_id = $para->country_id;
                             if ($this->addMetaInfoToDatabase($para->post_id, "country_id", $internalflightBO->country_id) == NULL) {
                                 $this->db->rollBack();
                                 if (isset($imageModel) && isset($country_id)) {
                                     $imageModel->delete($country_id);
                                 }
                                 $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                 return FALSE;
                             }
                         } else {
                             if ($internalflightBO->country_id != $para->country_id) {
                                 $internalflightBO->country_id = $para->country_id;
                                 if (!$this->updateMetaInfoToDatabase($para->post_id, "country_id", $internalflightBO->country_id)) {
                                     $this->db->rollBack();
                                     if (isset($imageModel) && isset($country_id)) {
                                         $imageModel->delete($country_id);
                                     }
                                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                                     return FALSE;
                                 }
                             }
                         }
                     }
                     if (isset($para->tag_array) || isset($internalflightBO->tag_list)) {
                         Model::autoloadModel('tag');
                         $tagModel = new TagModel($this->db);
                         Model::autoloadModel('taxonomy');
                         $taxonomyModel = new TaxonomyModel($this->db);
                         if (!isset($para->tag_array) || count($para->tag_array) == 0) {
                             foreach ($internalflightBO->tag_list as $tag) {
                                 $tagModel->deleteRelationship($para->post_id, $tag->term_taxonomy_id);
                             }
                         } elseif (!isset($internalflightBO->tag_list) || count($internalflightBO->tag_list) == 0) {
                             if (count($para->tag_array) > 0) {
                                 $tag_id_array = $tagModel->addTagArray($para->tag_array);
                                 for ($i = 0; $i < count($tag_id_array); $i++) {
                                     $taxonomyModel->addRelationshipToDatabase($para->post_id, $tag_id_array[$i]);
                                 }
                             }
                         } elseif (isset($para->tag_array) && isset($internalflightBO->tag_list) && count($para->tag_array) > 0 && count($internalflightBO->tag_list) > 0) {
                             $tags_old_array = array();
                             foreach ($internalflightBO->tag_list as $tag_old) {
                                 $tags_old_array[] = $tag_old->name;
                             }
                             $tags_new_array = array();
                             for ($i = 0; $i < count($para->tag_array); $i++) {
                                 if (!in_array($para->tag_array[$i], $tags_old_array)) {
                                     $tags_new_array[] = $para->tag_array[$i];
                                 }
                             }
                             if (count($tags_new_array) > 0) {
                                 $tag_id_new_array = $tagModel->addTagArray($tags_new_array);
                                 for ($i = 0; $i < count($tag_id_new_array); $i++) {
                                     $taxonomyModel->addRelationshipToDatabase($para->post_id, $tag_id_new_array[$i]);
                                 }
                             }
                             $tags_delete_array = array();
                             for ($i = 0; $i < count($internalflightBO->tag_list); $i++) {
                                 if (!in_array($internalflightBO->tag_list[$i]->name, $para->tag_array)) {
                                     $tags_delete_array[] = $internalflightBO->tag_list[$i];
                                 }
                             }
                             if (count($tags_delete_array) > 0) {
                                 foreach ($tags_delete_array as $tag) {
                                     $tagModel->deleteRelationship($para->post_id, $tag->term_taxonomy_id);
                                 }
                             }
                         }
                     }
                     $this->db->commit();
                     if (isset($imageModel) && isset($image_id) && isset($image_id_old)) {
                         $imageModel->delete($image_id_old);
                     }
                     $_SESSION["fb_success"][] = UPDATE_INTERNALFLIGHT_SUCCESS;
                     return TRUE;
                 } else {
                     $this->db->rollBack();
                     if (isset($imageModel) && isset($image_id)) {
                         $imageModel->delete($image_id);
                     }
                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
                 }
             }
         }
     } catch (Exception $e) {
         $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_INTERNALFLIGHT;
     }
     return FALSE;
 }
Esempio n. 15
0
<?php

$tag_name = $_GET['TagName'];
$brand_name = $_GET['BrandName'];
$style_id = $_GET['StyleId'];
if (trim($tag_name) !== "") {
    $connection = Yii::app()->db;
    //搜索 tag 表中是否存在此次上送的 名字。 如果没有就插入记录。
    $tagModel = new TagModel();
    $ret = TagModel::model()->find('name=:tag_name', array(':tag_name' => $tag_name));
    if (!isset($ret)) {
        $tagModel->name = $tag_name;
        $tagModel->create_time = time();
        $tagModel->save();
    }
    //找到名字对应的_id。以便做插入 rel 关系表的时候用
    $sql = "select _id from tbl_tag where name = :TagName";
    $command = $connection->createCommand($sql);
    $tag_id = $command->query(array(':TagName' => $tag_name))->readAll();
    if (isset($tag_id)) {
        //插入 tbl_style_tag_rel 表
        $styleTagRelModel = new StyleTagRelModel();
        $styleTagRelModel->style_id = $style_id;
        $styleTagRelModel->tag_id = $tag_id[0]['_id'];
        $styleTagRelModel->tag_name = $brand_name;
        $styleTagRelModel->create_time = time();
        $styleTagRelModel->save();
    }
}
$sql = "select B.name as tag_name, A.tag_name as brand_name\n\t\t\tfrom tbl_style_tag_rel A\n\t\t\tinner join tbl_tag B on B._id =  A.tag_id\n\t\t\twhere A.style_id = :style_id order by B.name asc";
$command = $connection->createCommand($sql);
Esempio n. 16
0
 function run($db, $type)
 {
     $test = new \Test();
     // setup
     ///////////////////////////////////
     $author = new \AuthorModel();
     $news = new \NewsModel();
     $profile = new \ProfileModel();
     $tag = new \TagModel();
     $ac = $author::resolveConfiguration();
     $author_pk = is_int(strpos($type, 'sql')) ? $ac['primary'] : '_id';
     $nc = $news::resolveConfiguration();
     $news_pk = is_int(strpos($type, 'sql')) ? $nc['primary'] : '_id';
     $tc = $tag::resolveConfiguration();
     $tag_pk = is_int(strpos($type, 'sql')) ? $tc['primary'] : '_id';
     $authorIDs = $author->find()->getAll('_id');
     $all = $news->find();
     $newsIDs = $all->getAll('_id');
     $profileIDs = $profile->find()->getAll('_id');
     $tagIDs = $tag->find()->getAll('_id');
     // add another relation
     $news->load(array('title = ?', 'CSS3 Showcase'));
     $news->author = $author->load(array($author_pk . ' = ?', $authorIDs[0]));
     $news->save();
     $news->reset();
     $author->reset();
     // has-filter on belongs-to relation
     ///////////////////////////////////
     $result = $author->has('news', array('title like ?', '%Image%'))->afind();
     $test->expect(count($result) == 1 && $result[0]['name'] == 'Johnny English', $type . ': has filter on many-to-one field');
     $test->expect(count($result[0]['news']) == 2 && $result[0]['news'][0]['title'] == 'Responsive Images' && $result[0]['news'][1]['title'] == 'CSS3 Showcase', $type . ': has filter does not prune relation set');
     $result = $news->has('author', array('name = ?', 'Johnny English'))->afind();
     $test->expect(count($result) == 2 && $result[0]['title'] == 'Responsive Images' && $result[1]['title'] == 'CSS3 Showcase', $type . ': has filter on one-to-many field');
     // add another profile
     $profile->message = 'Beam me up, Scotty!';
     $profile->author = $authorIDs[2];
     $profile->save();
     $profile->reset();
     $result = $author->has('profile', array('message LIKE ?', '%Scotty%'))->afind();
     $test->expect(count($result) == 1 && $result[0]['name'] == 'James T. Kirk' && $result[0]['profile']['message'] == 'Beam me up, Scotty!', $type . ': has filter on one-to-one field');
     $result = $profile->has('author', array('name LIKE ?', '%Kirk%'))->afind();
     $test->expect(count($result) == 1 && $result[0]['message'] == 'Beam me up, Scotty!' && $result[0]['author']['name'] == 'James T. Kirk', $type . ': has filter on one-to-one field, inverse');
     // add mm tags
     $news->load(array('title = ?', 'Responsive Images'));
     $news->tags2 = array($tagIDs[0], $tagIDs[1]);
     $news->save();
     $news->load(array('title = ?', 'CSS3 Showcase'));
     $news->tags2 = array($tagIDs[1], $tagIDs[2]);
     $news->save();
     $news->reset();
     $result = $news->has('tags2', array('title like ?', '%Design%'))->find();
     $test->expect(count($result) == 1 && $result[0]['title'] == 'Responsive Images', $type . ': has filter on many-to-many field');
     $result = $news->has('tags2', array('title = ?', 'Responsive'))->find();
     $test->expect(count($result) == 2 && $result[0]['title'] == 'Responsive Images' && $result[1]['title'] == 'CSS3 Showcase', $type . ': has filter on many-to-many field, additional test');
     $result = $tag->has('news', array('title = ?', 'Responsive Images'))->find();
     $test->expect(count($result) == 2 && $result[0]['title'] == 'Web Design' && $result[1]['title'] == 'Responsive', $type . ': has filter on many-to-many field, inverse');
     // add another tag
     $news->load(array('title = ?', 'Touchable Interfaces'));
     $news->tags2 = array($tagIDs[1]);
     $news->save();
     $news->reset();
     $tag->has('news', array('text LIKE ? and title LIKE ?', '%Lorem%', '%Interface%'));
     $result = $tag->find();
     $test->expect(count($result) == 1 && $result[0]['title'] == 'Responsive', $type . ': has filter with multiple conditions');
     $news->has('tags2', array('title = ? OR title = ?', 'Usability', 'Web Design'));
     $result = $news->afind(array('text = ?', 'Lorem Ipsun'));
     $test->expect(count($result) == 1 && $result[0]['title'] == 'Responsive Images', $type . ': find with condition and has filter');
     $news->load(array('title = ?', 'Responsive Images'));
     $news->author = $authorIDs[1];
     $news->save();
     $news->reset();
     $news->has('tags2', array('title = ? OR title = ?', 'Usability', 'Web Design'));
     $news->has('author', array('name = ?', 'Ridley Scott'));
     $result = $news->afind();
     $test->expect(count($result) == 1 && $result[0]['title'] == 'Responsive Images', $type . ': find with multiple has filters on different relations');
     // add another news to author 2
     $news->load(array($news_pk . ' = ?', $newsIDs[2]));
     $news->author = $authorIDs[1];
     $news->save();
     $news->reset();
     $news->has('author', array('name = ?', 'Ridley Scott'));
     $news->load();
     $res = array();
     while (!$news->dry()) {
         $res[] = $news->title;
         $news->next();
     }
     $test->expect(count($res) == 2 && $res[0] == 'Responsive Images' && $res[1] == 'Touchable Interfaces', $type . ': has filter in load context');
     $news->reset();
     $news->fields(array('title'));
     $news->load();
     $test->expect(!empty($news->title) && empty($news->author) && empty($news->text) && empty($news->tags) && empty($news->tags2), $type . ': use a whitelist to restrict fields');
     unset($news);
     $news = new \NewsModel();
     $news->fields(array('title', 'tags', 'tags2', 'author'), true);
     $news->load();
     $test->expect(empty($news->title) && empty($news->author) && !empty($news->text) && empty($news->tags) && empty($news->tags2), $type . ': use a blacklist to restrict fields');
     unset($news);
     $news = new \NewsModel();
     $news->fields(array('tags.title'));
     $news->load();
     $test->expect(!empty($news->tags[0]->title) && empty($news->tags[0]->news), $type . ': set restricted fields to related mappers');
     $news->filter('tags2', null, array('order' => 'title ASC'));
     $news->load(array('title = ?', 'Responsive Images'));
     $test->expect($news->tags2[0]->title == 'Responsive' && $news->tags2[1]->title == 'Web Design', $type . ': filter with sorting of related records');
     // get all tags sorted by their usage in news articles
     $tag->reset();
     $tag->countRel('news');
     $result = $tag->find(null, array('order' => 'count_news DESC, title'))->castAll(0);
     $test->expect($result[0]['title'] == 'Responsive' && $result[0]['count_news'] == 3 && $result[1]['title'] == 'Usability' && $result[1]['count_news'] == 1 && $result[2]['title'] == 'Web Design' && $result[2]['count_news'] == 1, $type . ': count and sort on many-to-many relation');
     // get all authors sorted by the amount of news they have written
     $author->reset();
     $author->countRel('news');
     $result = $author->find(null, array('order' => 'count_news DESC'))->castAll(0);
     $test->expect($result[0]['name'] == 'Ridley Scott' && $result[0]['count_news'] == 2 && $result[1]['name'] == 'Johnny English' && $result[1]['count_news'] == 1 && $result[2]['name'] == 'James T. Kirk' && $result[2]['count_news'] == null, $type . ': count and sort on one-to-many relation');
     $tag->reset();
     $tag->countRel('news');
     $result = $tag->find(null, array('order' => 'count_news DESC, title DESC', 'limit' => 1, 'offset' => 1))->castAll(0);
     $test->expect($result[0]['title'] == 'Web Design' && $result[0]['count_news'] == 1, $type . ': apply limit and offset on aggregated collection');
     $author->reset();
     $author->countRel('news');
     $author->has('news', array('text like ?', '%Lorem%'));
     $result = $author->find()->castAll(0);
     $test->expect(count($result) == 1 && $result[0]['name'] == 'Ridley Scott' && $result[0]['count_news'] == 2, $type . ': has-filter and 1:M relation counter');
     $author->reset();
     $id = $author->load()->next()->_id;
     $tag->reset();
     $tag->countRel('news');
     $tag->has('news', array('author = ?', $id));
     $result = $tag->find(null, array('order' => 'count_news desc'))->castAll(0);
     $test->expect(count($result) == 2 && $result[0]['title'] == 'Responsive' && $result[0]['count_news'] == 3 && $result[1]['title'] == 'Web Design' && $result[1]['count_news'] == 1, $type . ': has-filter and M:M relation counter');
     ///////////////////////////////////
     return $test->results();
 }
Esempio n. 17
0
 /**
  * Delete a Tag
  *
  * @param Gdn_Controller $Sender
  */
 public function Controller_Delete($Sender)
 {
     $Sender->Permission('Garden.Settings.Manage');
     $TagID = GetValue(1, $Sender->RequestArgs);
     $TagModel = new TagModel();
     $Tag = $TagModel->GetID($TagID, DATASET_TYPE_ARRAY);
     if ($Sender->Form->AuthenticatedPostBack()) {
         // Delete tag & tag relations.
         $SQL = Gdn::SQL();
         $SQL->Delete('TagDiscussion', array('TagID' => $TagID));
         $SQL->Delete('Tag', array('TagID' => $TagID));
         $Sender->InformMessage(FormatString(T('<b>{Name}</b> deleted.'), $Tag));
         $Sender->JsonTarget("#Tag_{$Tag['TagID']}", NULL, 'Remove');
     }
     $Sender->SetData('Title', T('Delete Tag'));
     $Sender->Render('delete', '', 'plugins/Tagging');
 }
Esempio n. 18
0
 public function actionUpStyle()
 {
     $connection = Yii::app()->db;
     $Cates = array();
     $Tags = array();
     $isSuc = false;
     $userId = $_REQUEST['id'];
     $picDesc = $_REQUEST['desc'];
     $category_name = $_REQUEST['category_name'];
     $tag_name = $_REQUEST['tag_name'];
     $categories = explode(",", $category_name);
     $tags = explode(",", $tag_name);
     //本地
     //$root = YiiBase::getPathOfAlias('webroot').Yii::app()->getBaseUrl();
     //服务器代码
     $root = YiiBase::getPathOfAlias('webroot');
     $folder = $root . '/images/images/styles/' . $userId . '/';
     $desFilePath;
     $tmpFilePath;
     $relPath = Yii::app()->getBaseUrl() . '/images/images/styles/' . $userId . '/';
     //echo ($folder);
     //exit();
     $this->mkDirIfNotExist($folder);
     if ($_FILES["file"]["type"] == "image/gif" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/png" || $_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/pjpeg") {
         if ($_FILES["file"]["error"] > 0) {
             $isSuc = false;
         } else {
             $tmpFilePath = $_FILES["file"]["tmp_name"];
             /*
             				$array = explode("/", $tmpFilePath); 
             				var_dump($array[ count($array) -1]);
             			    $tmpPath  = $tmpPath.$array[ count($array) -1];
             */
             $name = $this->getUploadImageFileName($_FILES["file"]["name"]);
             $desFilePath = $folder . $name;
             $desThumbPath = $folder . 'thumb/' . $name;
             $relPath = $relPath . $name;
             if (file_exists($desFilePath)) {
                 unlink($desFilePath);
                 //echo $_FILES["file"]["name"] . " already exists. ";
             } else {
                 move_uploaded_file($tmpFilePath, $desFilePath);
                 //生成缩略图
                 $im = null;
                 $imtp = null;
                 if ($_FILES["file"]["type"] == "image/gif") {
                     $im = imagecreatefromgif($desFilePath);
                     $imtp = 'gif';
                 } else {
                     if ($_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg") {
                         $im = imagecreatefromjpeg($desFilePath);
                         $imtp = 'jpg';
                     } else {
                         if ($_FILES["file"]["type"] == "image/png") {
                             $im = imagecreatefrompng($desFilePath);
                             $imtp = 'png';
                         }
                     }
                 }
                 $this->mkDirIfNotExist($folder . 'thumb/');
                 CThumb::resizeImage($im, 100, 100, $desThumbPath, $imtp);
                 //------------生成缩略图
                 $isSuc = true;
             }
         }
     } else {
         $isSuc = false;
     }
     if ($isSuc) {
         $styleModel = new StyleModel();
         $tagModel = new TagModel();
         $categoryModel = new CategoryModel();
         $styleModel->image = $relPath;
         $styleModel->user_id = $userId;
         $styleModel->create_time = time();
         $styleModel->like_num = 0;
         $styleModel->recommand_val = 0;
         if (!$styleModel->save()) {
             echo "style saved fail!";
             return false;
         }
         foreach ($categories as $cate_name) {
             //搜索 category 表中是否存在此次上送的 名字。 如果没有就插入记录。
             $ret = CategoryModel::model()->find('name=:cate_name', array(':cate_name' => $cate_name));
             if (!isset($ret)) {
                 $categoryModel->name = $cate_name;
                 $categoryModel->create_time = time();
                 if (!$categoryModel->save()) {
                     echo "category zd fail!";
                 }
             }
             //找到名字对应的_id。以便做插入 rel 关系表的时候用
             $sql = "select _id from tbl_category where name = :CateName";
             $command = $connection->createCommand($sql);
             $tmp = $command->query(array(':CateName' => $cate_name))->readAll();
             array_push($Cates, array('cate_id' => $tmp[0]["_id"]));
         }
         foreach ($tags as $tag_name) {
             //搜索 tag 表中是否存在此次上送的 名字。 如果没有就插入记录。
             $ret = TagModel::model()->find('name=:tag_name', array(':tag_name' => $tag_name));
             if (!isset($ret)) {
                 $tagModel->name = $tag_name;
                 $tagModel->create_time = time();
                 if (!$tagModel->save()) {
                     echo "tag saved fail!";
                 }
             }
             //找到名字对应的_id。以便做插入 rel 关系表的时候用
             $sql = "select _id from tbl_tag where name = :TagName";
             $command = $connection->createCommand($sql);
             $tmp = $command->query(array(':TagName' => $tag_name))->readAll();
             array_push($Tags, array('tag_id' => $tmp[0]["_id"]));
         }
         //插入 tbl_style_category_rel 表 ( 可优化。 改成批量插入 )
         foreach ($Cates as $Cate) {
             $styleCateRelModel = new StyleCateRelModel();
             $styleCateRelModel->style_id = $styleModel->_id;
             $styleCateRelModel->category_id = $Cate['cate_id'];
             $styleModel->create_time = time();
             if (!$styleCateRelModel->save()) {
                 echo "styleCateRel saved fail!";
             }
         }
         //插入 tbl_style_tag_rel 表 ( 可优化。 改成批量插入 )
         foreach ($Tags as $Tag) {
             $styleTagRelModel = new StyleTagRelModel();
             $styleTagRelModel->style_id = $styleModel->_id;
             $styleTagRelModel->tag_id = $Tag['tag_id'];
             $styleModel->create_time = time();
             if (!$styleTagRelModel->save()) {
                 echo "styleTagRel saved fail!";
             }
         }
         $host = 'http://' . Yii::app()->request->getServerName();
         //本地调试
         $styleModel->image = $host . $styleModel->image;
         //服务器
         //$styleModel->image = $host.Yii::app()->getBaseUrl().$styleModel->image;
         echo json_encode(array('result' => 1, 'res' => array('id' => $styleModel->_id, 'user_id' => $styleModel->user_id, 'image' => $styleModel->image)));
     } else {
         echo json_encode(array('result' => 0));
     }
 }
 /**
  * Saves a tag.
  */
 public function actionSaveTag()
 {
     $this->requirePostRequest();
     $tagId = craft()->request->getPost('tagId');
     if ($tagId) {
         $tag = craft()->tags->getTagById($tagId, craft()->locale->id);
         if (!$tag) {
             throw new Exception(Craft::t('No tag exists with the ID “{id}”', array('id' => $tagId)));
         }
     } else {
         $tag = new TagModel();
     }
     // Set the tag attributes, defaulting to the existing values for whatever is missing from the post data
     $tag->groupId = craft()->request->getPost('groupId', $tag->groupId);
     $tag->getContent()->title = craft()->request->getPost('title', $tag->title);
     $tag->setContentFromPost('fields');
     if (craft()->tags->saveTag($tag)) {
         craft()->userSession->setNotice(Craft::t('Tag saved.'));
         $this->redirectToPostedUrl($tag);
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save tag.'));
         // Send the tag back to the template
         craft()->urlManager->setRouteVariables(array('tag' => $tag));
     }
 }
Esempio n. 20
0
 /**
  * Delete a Tag
  *
  * @param Gdn_Controller $Sender
  */
 public function controller_delete($Sender)
 {
     $Sender->permission('Garden.Settings.Manage');
     $TagID = val(1, $Sender->RequestArgs);
     $TagModel = new TagModel();
     $Tag = $TagModel->getID($TagID, DATASET_TYPE_ARRAY);
     if ($Sender->Form->authenticatedPostBack()) {
         // Delete tag & tag relations.
         $SQL = Gdn::sql();
         $SQL->delete('TagDiscussion', array('TagID' => $TagID));
         $SQL->delete('Tag', array('TagID' => $TagID));
         $Sender->informMessage(formatString(t('<b>{Name}</b> deleted.'), $Tag));
         $Sender->jsonTarget("#Tag_{$Tag['TagID']}", null, 'Remove');
     }
     $Sender->setData('Title', t('Delete Tag'));
     $Sender->render('delete', '', 'plugins/Tagging');
 }
Esempio n. 21
0
 public function searchAjax($str = NULL)
 {
     Model::autoloadModel('tag');
     $model = new TagModel($this->db);
     $this->para = new stdClass();
     if (isset($str) && $str != NULL && $str != "") {
         $this->para->s = $str;
         $this->view->s = $str;
     } elseif (isset($_POST['s'])) {
         $this->para->s = $_POST['s'];
         $this->view->s = $_POST['s'];
     }
     $model->searchAjax($this->view, $this->para);
     $this->view->renderAdmin(RENDER_SEARCH_TAG_AJAX, TRUE);
 }
Esempio n. 22
0
 public function loadEntries()
 {
     $totalPosts = 0;
     $retVal = $totalPosts;
     /* REFERENCE MATERIALS */
     // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
     $categoriesXml = simplexml_load_file('http://40act.ee/export/categories');
     //echo 'XML loaded<br />';
     $tagSetId = 1;
     $sectionId = 0;
     // Visit settings for your Section and check the URL
     $typeId = 0;
     // Visit Entry Types for your Section and check the URL for the Entry Type
     $referenceUrlTypeId = 0;
     $categoryFieldId = 0;
     // Field in entry type for category relation
     $debug = true;
     $debugCategories = false;
     $debugReference = false;
     $debugSubjects = false;
     $debugHowTo = false;
     $debugStatute = false;
     $debugRules = false;
     $debugOtherRules = false;
     $debugNews = false;
     $save = true;
     $run_categories = false;
     $run_reference_materials = false;
     $run_subjects = false;
     $run_howto = false;
     $run_statute = false;
     $run_rules = false;
     $run_other_rules = false;
     $run_subjects_redline = false;
     $run_subjects_blueline = false;
     $run_subjects_orangeline = false;
     $run_howto_redline = false;
     $run_howto_greenline = false;
     $run_howto_orangeline = false;
     $run_statute_redline = false;
     $run_statute_greenline = false;
     $run_statute_blueline = false;
     $run_rules_redline = false;
     $run_rules_greenline = false;
     $run_rules_blueline = false;
     $run_other_rules_redline = false;
     $run_other_rules_greenline = false;
     $run_other_rules_blueline = false;
     $run_news = false;
     $run_reference_default_investment_advisers = false;
     if ($run_reference_default_investment_advisers) {
         $entries = craft()->elements->getCriteria(ElementType::Entry);
         $entries->section = 'referenceMaterials';
         //$entries->limit = 1;
         $existingEntries = $entries->find();
         foreach ($existingEntries as $existingEntry) {
             echo 'id: ' . $existingEntry->id . '<br />';
             $entryToSave = new EntryModel();
             $entryToSave = $existingEntry;
             // Setting these in case they're required to be set for saveEntry()
             $entryToSave->sectionId = 9;
             $entryToSave->typeId = 9;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             $entryToSave->getContent()->title = $existingEntry->title;
             $entryToSave->getContent()->showInInvestmentAdvisersReference = 1;
             if (craft()->entries->saveEntry($entryToSave)) {
                 echo 'saved<br />';
             } else {
                 echo 'not saved<br />';
                 var_dump($entryToSave->getAllErrors());
                 //echo implode(', ', $entryToSave()->getAllErrors() );
                 // RESTORE REQUIRED STATUS on Document ID, Reference Item Name, Files
             }
         }
     }
     if ($run_categories) {
         // Let's import all the Reference Material categories FIRST, and capture their legacy ID
         foreach ($categoriesXml->reference_categories[0]->category as $importCategory) {
             //var_dump($importCategory);
             if ($debugCategories) {
                 // Imported/feed category details display
                 echo 'id: ' . $importCategory->id . '<br />';
                 echo 'parent id: ' . $importCategory->parent_id . '<br />';
                 echo 'url title/slug: ' . $importCategory->category_url_title . '<br />';
                 echo $importCategory->name . '<br />';
             }
             // Let's see if this category exists or not...
             $categories = craft()->elements->getCriteria(ElementType::Category);
             $categories->groupId = 1;
             $categories->legacyId = $importCategory->id;
             $categories->limit = 1;
             $category = $categories->find();
             $categoryToSave = new CategoryModel();
             $categoryToSave->groupId = 1;
             $categoryToSave->enabled = true;
             // Did we find a match?
             if (count($category) == 1) {
                 foreach ($category as $existingCategory) {
                     // Use the existing category instead of saving a new category
                     $categoryToSave = $existingCategory;
                     if ($debugCategories) {
                         'We have an existing category to update.<br />';
                     }
                 }
             }
             // If parent_id == 0, omit setting parent
             if ($importCategory->parent_id != 0) {
                 if ($debugCategories) {
                     echo 'We have a parent category!<br />';
                 }
                 $parentCategories = craft()->elements->getCriteria(ElementType::Category);
                 $parentCategories->groupId = 1;
                 $parentCategories->legacyId = $importCategory->parent_id;
                 $parentCategories->limit = 1;
                 $parentCategory = $parentCategories->find();
                 // We are assuming that the source feed outputs the nested categories in order, so the
                 // parent category should already exist. I.e., we don't need to create it if not found.
                 if (count($parentCategory) == 1) {
                     foreach ($parentCategory as $existingParentCategory) {
                         if ($debugCategories) {
                             echo 'Craft parent ID: ' . $existingParentCategory->id . '<br />';
                         }
                         $categoryToSave->newParentId = $existingParentCategory->id;
                         $categoryToSave->setParent($existingParentCategory);
                     }
                 }
             }
             $categoryToSave->slug = $importCategory->category_url_title;
             $categoryToSave->getContent()->title = $importCategory->name;
             $categoryToSave->getContent()->legacyId = $importCategory->id;
             // This will automatically save the category if it does not already exist
             // We've either set the attributes of a new categories, or updated the attributes of a found category
             craft()->categories->saveCategory($categoryToSave);
             //$saveCategory = true;
             if ($debugCategories) {
                 echo '<br />';
             }
         }
     }
     // Then we can just synch each Reference Material entry's applied categories by ID, without dealing with parent categories and matches in this sitepoint
     if ($run_reference_materials) {
         // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
         $referenceMaterialsXml = simplexml_load_file('http://40act.craft.dev:8888/reference-materials.xml');
         // Replace with Reference Materials feed
         $sectionId = 9;
         // Visit settings for your Section and check the URL
         $typeId = 9;
         // Visit Entry Types for your Section and check the URL for the Entry Type
         $referenceUrlTypeId = 10;
         $categoryFieldId = 0;
         // Field in entry type for category relation
         foreach ($referenceMaterialsXml->reference_materials[0]->item as $importItem) {
             // Note that the URL field has not been used on the EE site, so we're not going to import the URL entry type (10)
             $referenceItem = array();
             $referenceItem['entry_id'] = (string) $importItem->id;
             // x $entryUrlTitle
             $referenceItem['slug'] = (string) $importItem->slug;
             // x $entryDate
             $referenceItem['entryDate'] = $importItem->entry_date;
             // x $entryStatus
             $referenceItem['entryStatus'] = (string) $importItem->status;
             // x $entryTitle
             $referenceItem['entryTitle'] = (string) $importItem->title;
             // x $entryDocumentId
             $referenceItem['entryDocumentId'] = (string) $importItem->document_id;
             // x $entryItemName
             $referenceItem['entryItemName'] = (string) $importItem->item_name;
             // x $entryPubDate
             $referenceItem['pubDate'] = $importItem->pub_date;
             // x $entryFiles – Need to loop through and look up assets
             //               Also need to load asset fields – Title, caption, others?
             $filesArray = array();
             $assetsToSave = array();
             foreach ($importItem->files->file as $referenceFile) {
                 $assets = craft()->elements->getCriteria(ElementType::Asset);
                 $assets->filename = $referenceFile->filename;
                 $assets->limit = 1;
                 $assetId = 0;
                 foreach ($assets as $assetMatched) {
                     $assetId = $assetMatched->id;
                 }
                 $filesArray[] = array($referenceFile->title, $referenceFile->filename, $assetId);
                 $assetsToSave[] = $assetId;
             }
             $saveAssets = false;
             if (count($assetsToSave) > 0) {
                 $saveAssets = true;
             }
             $referenceItem['entryFiles'] = $filesArray;
             // x $entrySource – Simply load text value into plaintext field
             $referenceItem['entrySource'] = $importItem->source;
             // x $entryDescription – Rich text
             $referenceItem['entryDescription'] = $importItem->description;
             // x $entryContent – Rich text
             $referenceItem['entryContent'] = $importItem->content;
             // x $entryCategories – For each category's legacy ID, create/save a category link to an already imported entry based on legacy ID
             $categoriesLegacyArray = array();
             $categoriesToSave = array();
             foreach ($importItem->categories->category_id as $categoryId) {
                 $categoriesLegacyArray[] = $categoryId;
                 $categories = craft()->elements->getCriteria(ElementType::Category);
                 $categories->groupId = 1;
                 $categories->legacyId = (string) $categoryId;
                 $categories->limit = 1;
                 $category = $categories->first();
                 // There should always be a match
                 if (count($category) > 0) {
                     $categoriesToSave[] = $category->id;
                 }
             }
             $referenceItem['categoryLegacyIds'] = $categoriesLegacyArray;
             $referenceItem['categoryCraftIds'] = $categoriesToSave;
             // But we don't want to set an empty array in our entry save.
             $saveCategory = false;
             if (count($categoriesToSave) > 0) {
                 $saveCategory = true;
             }
             // x $entryTags
             $tagsArray = array();
             $tagsToSave = array();
             foreach ($importItem->tags->tag as $tag) {
                 // Need to look up / create tag if it does not exist
                 $tagToFind = craft()->elements->getCriteria(ElementType::Tag);
                 $tagToFind->title = (string) $tag;
                 $tagToFind->limit = 1;
                 $tagToFind->groupId = $tagSetId;
                 $existingTag = $tagToFind->find();
                 if (count($existingTag) == 0) {
                     $tagToSave = new TagModel();
                     $tagToSave->groupId = $tagSetId;
                     $tagToSave->getContent()->setAttributes(array('title' => (string) $tag));
                     craft()->tags->saveTag($tagToSave);
                 }
                 $tagToSave = $tagToFind->first();
                 $tagsArray[] = array($tag, $tagToSave->id);
                 $tagsToSave[] = $tagToSave->id;
             }
             $referenceItem['tags'] = $tagsToSave;
             $saveTags = false;
             if (count($tagsToSave) > 0) {
                 $saveTags = true;
             }
             if ($debugReference) {
                 echo '<br />***<br /><br />';
                 foreach ($referenceItem as $key => $value) {
                     echo $key . ': ';
                     if (is_array($referenceItem[$key])) {
                         echo '<br />';
                         foreach ($referenceItem[$key] as $arrayItem) {
                             if (is_array($arrayItem)) {
                                 foreach ($arrayItem as $subArrayItem) {
                                     echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $subArrayItem . '<br />';
                                 }
                             } else {
                                 echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $arrayItem . '<br />';
                             }
                         }
                     } else {
                         echo $referenceItem[$key] . '<br />';
                     }
                 }
             }
             // Default page protected to Yes
             // Save the entry
             if (!$save) {
                 continue;
             }
             $entry = craft()->elements->getCriteria(ElementType::Entry);
             $entry->section = 'referenceMaterials';
             $entry->limit = 1;
             $entry->slug = (string) $referenceItem['slug'];
             $existingEntry = $entry->find();
             $entryToSave = new EntryModel();
             if (count($existingEntry > 0)) {
                 foreach ($existingEntry as $existingEntry) {
                     $entryToSave = $existingEntry;
                 }
             }
             $entryToSave->sectionId = $sectionId;
             $entryToSave->typeId = $typeId;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             if ($referenceItem['entryStatus'] == 'closed') {
                 $entryToSave->enabled = false;
             }
             $entryToSave->postDate = date('Y-m-d h:m:s', (double) $referenceItem['entryDate']);
             $entryToSave->slug = $referenceItem['slug'];
             $entryToSave->getContent()->setAttributes(array('title' => $referenceItem['entryTitle'], 'referenceItemDocumentId' => $referenceItem['entryDocumentId'], 'referenceItemName' => $referenceItem['entryItemName'], 'referenceItemSource' => $referenceItem['entrySource'], 'referenceItemPubDate' => date('Y-m-d h:m:s', (double) $referenceItem['pubDate']), 'referenceItemDescription' => $referenceItem['entryDescription'], 'referenceItemContent' => $referenceItem['entryContent'], 'isProtected' => 1, 'legacyId' => $referenceItem['entry_id']));
             if ($saveAssets) {
                 $entryToSave->getContent()->referenceItemFiles = $assetsToSave;
             }
             if ($saveCategory) {
                 $entryToSave->getContent()->referenceItemCategories = $categoriesToSave;
             }
             if ($saveTags) {
                 $entryToSave->getContent()->referenceItemTags = $tagsToSave;
             }
             if (craft()->entries->saveEntry($entryToSave)) {
                 $totalPosts++;
                 $retVal = $totalPosts;
                 continue;
             } else {
                 $retVal = false;
             }
         }
     }
     if ($run_subjects) {
         // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
         $subjectsXml = simplexml_load_file('http://40act.craft.dev:8888/subjects.xml');
         $sectionId = 3;
         // Visit settings for your Section and check the URL
         $typeId = 3;
         // Visit Entry Types for your Section and check the URL for the Entry Type
         foreach ($subjectsXml->subjects[0]->item as $importItem) {
             $subjectItem = array();
             // Need to load as legacy ID for parent ID lookups, re-import (though reference re-import was based on slug)
             $subjectItem['entry_id'] = (string) $importItem->id;
             // $entryUrlTitle
             $subjectItem['slug'] = (string) $importItem->slug;
             // $entryDate
             $subjectItem['entryDate'] = $importItem->entry_date;
             // $entryStatus
             $subjectItem['entryStatus'] = (string) $importItem->status;
             // $entryTitle
             $subjectItem['entryTitle'] = (string) $importItem->title;
             // $entryContent – Rich text
             $subjectItem['entryContent'] = $importItem->content;
             // tags
             $tagsToSave = array();
             foreach ($importItem->tags->tag as $tag) {
                 // Need to look up / create tag if it does not exist
                 $tagToFind = craft()->elements->getCriteria(ElementType::Tag);
                 $tagToFind->title = (string) $tag;
                 $tagToFind->limit = 1;
                 $tagToFind->groupId = $tagSetId;
                 $existingTag = $tagToFind->find();
                 if (count($existingTag) == 0) {
                     $tagToSave = new TagModel();
                     $tagToSave->groupId = $tagSetId;
                     $tagToSave->getContent()->setAttributes(array('title' => (string) $tag));
                     craft()->tags->saveTag($tagToSave);
                 }
                 $tagToSave = $tagToFind->first();
                 $tagsArray[] = array($tag, $tagToSave->id);
                 $tagsToSave[] = $tagToSave->id;
             }
             $subjectItem['tags'] = $tagsToSave;
             $saveTags = false;
             if (count($tagsToSave) > 0) {
                 $saveTags = true;
             }
             if ($debugSubjects) {
                 echo '<br />***<br /><br />';
                 foreach ($subjectItem as $key => $value) {
                     echo $key . ': ';
                     if (is_array($subjectItem[$key])) {
                         echo '<br />';
                         foreach ($subjectItem[$key] as $arrayItem) {
                             if (is_array($arrayItem)) {
                                 foreach ($arrayItem as $subArrayItem) {
                                     echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $subArrayItem . '<br />';
                                 }
                             } else {
                                 echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $arrayItem . '<br />';
                             }
                         }
                     } else {
                         echo $subjectItem[$key] . '<br />';
                     }
                 }
             }
             // Save the entry
             if (!$save) {
                 continue;
             }
             $entry = craft()->elements->getCriteria(ElementType::Entry);
             $entry->section = 'investmentAdvisersSubjects';
             $entry->limit = 1;
             $entry->slug = (string) $subjectItem['slug'];
             $existingEntry = $entry->find();
             $entryToSave = new EntryModel();
             if (count($existingEntry > 0)) {
                 foreach ($existingEntry as $existingEntry) {
                     $entryToSave = $existingEntry;
                 }
             }
             // If parent_id == 0, omit setting parent
             if ($importItem->parent_id != 276) {
                 if ($debugSubjects) {
                     echo 'We have a parent entry!<br />';
                 }
                 $parentEntries = craft()->elements->getCriteria(ElementType::Entry);
                 $parentEntries->section = 'investmentAdvisersSubjects';
                 $parentEntries->legacyId = $importItem->parent_id;
                 $parentEntries->limit = 1;
                 $parentEntry = $parentEntries->find();
                 // We are assuming that the source feed outputs the nested categories in order, so the
                 // parent category should already exist. I.e., we don't need to create it if not found.
                 if (count($parentEntry) == 1) {
                     foreach ($parentEntry as $existingParentEntry) {
                         if ($debugSubjects) {
                             echo 'Craft parent ID: ' . $existingParentEntry->id . '<br />';
                         }
                         $entryToSave->parentId = $existingParentEntry->id;
                         $entryToSave->setParent($existingParentEntry);
                     }
                 }
             }
             $entryToSave->sectionId = $sectionId;
             $entryToSave->typeId = $typeId;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             if ($subjectItem['entryStatus'] == 'closed') {
                 $entryToSave->enabled = false;
             }
             $entryToSave->postDate = date('Y-m-d h:m:s', (double) $subjectItem['entryDate']);
             $entryToSave->slug = $subjectItem['slug'];
             $entryToSave->getContent()->setAttributes(array('title' => $subjectItem['entryTitle'], 'legacyId' => $subjectItem['entry_id'], 'pageContent' => $subjectItem['entryContent'], 'isProtected' => 1));
             if ($saveTags) {
                 $entryToSave->getContent()->pageTags = $tagsToSave;
             }
             if (craft()->entries->saveEntry($entryToSave)) {
                 $totalPosts++;
                 $retVal = $totalPosts;
                 continue;
             } else {
                 $retVal = false;
             }
         }
         if ($run_subjects_redline) {
             foreach ($subjectsXml->subjects[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersSubjects';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 //$entry->slug = $importItem->slug;
                 /*$entry->getContent()->setAttributes(array(
                       'legacyId' => (string)$importItem->id,
                   ));*/
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Treatise entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->redline->redline_item as $item) {
                     $referenceEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $referenceEntry->limit = 1;
                     $referenceEntry->legacyId = (string) $item->reference_item->reference_item_legacy_id;
                     /*$referenceEntry->getContent()->setAttributes(array(
                           'legacyId' => (string)$item->reference_item->reference_item_legacy_id,
                       ));*/
                     $entries = $referenceEntry->find();
                     if (count($entries) == 0) {
                         echo 'Reference Item entry not found! / EE ID: ' . (string) $item->reference_item->reference_item_legacy_id . '<br />';
                         continue;
                     }
                     $existingReferenceEntry = $referenceEntry->first();
                     echo 'Matrix: Reference Entry ID: ' . $existingReferenceEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 48;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 1;
                     $block->getContent()->setAttributes(array('entry' => [$existingReferenceEntry->id], 'annotation' => (string) $item->annotation));
                     craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_subjects_blueline) {
             foreach ($subjectsXml->subjects[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersSubjects';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Treatise entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->blueline->blueline_item as $item) {
                     $howtoEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $howtoEntry->limit = 1;
                     $howtoEntry->legacyId = (string) $item->legacy_id;
                     $entries = $howtoEntry->find();
                     if (count($entries) == 0) {
                         echo 'How-To entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingHowToEntry = $howtoEntry->first();
                     echo 'Matrix: How-To Entry ID: ' . $existingHowToEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 54;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 3;
                     $block->getContent()->setAttributes(array('entry' => [$existingHowToEntry->id], 'annotation' => (string) $item->annotation));
                     craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_subjects_orangeline) {
             foreach ($subjectsXml->subjects[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersSubjects';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Treatise entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->orangeline->orangeline_item as $item) {
                     $lawsrulesEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $lawsrulesEntry->limit = 1;
                     $lawsrulesEntry->legacyId = (string) $item->legacy_id;
                     $entries = $lawsrulesEntry->find();
                     if (count($entries) == 0) {
                         echo 'Laws & Rules entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingLawsRulesEntry = $lawsrulesEntry->first();
                     echo 'Matrix: Laws & Rules Entry ID: ' . $existingLawsRulesEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 57;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 4;
                     $block->getContent()->setAttributes(array('entry' => [$existingLawsRulesEntry->id], 'annotation' => (string) $item->annotation));
                     craft()->matrix->saveBlock($block);
                 }
             }
         }
     }
     if ($run_howto) {
         // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
         $howtoXml = simplexml_load_file('http://40act.craft.dev:8888/how-to.xml');
         $sectionId = 4;
         // Visit settings for your Section and check the URL
         $typeId = 4;
         // Visit Entry Types for your Section and check the URL for the Entry Type
         foreach ($howtoXml->entries[0]->item as $importItem) {
             $howtoItem = array();
             // Need to load as legacy ID for parent ID lookups, re-import (though reference re-import was based on slug)
             $howtoItem['entry_id'] = (string) $importItem->id;
             // $entryUrlTitle
             $howtoItem['slug'] = (string) $importItem->slug;
             // $entryDate
             $howtoItem['entryDate'] = $importItem->entry_date;
             // $entryStatus
             $howtoItem['entryStatus'] = (string) $importItem->status;
             // $entryTitle
             $howtoItem['entryTitle'] = (string) $importItem->title;
             // $entryContent – Rich text
             $howtoItem['entryContent'] = $importItem->content;
             // tags
             $tagsToSave = array();
             foreach ($importItem->tags->tag as $tag) {
                 // Need to look up / create tag if it does not exist
                 $tagToFind = craft()->elements->getCriteria(ElementType::Tag);
                 $tagToFind->title = (string) $tag;
                 $tagToFind->limit = 1;
                 $tagToFind->groupId = $tagSetId;
                 $existingTag = $tagToFind->find();
                 if (count($existingTag) == 0) {
                     $tagToSave = new TagModel();
                     $tagToSave->groupId = $tagSetId;
                     $tagToSave->getContent()->setAttributes(array('title' => (string) $tag));
                     craft()->tags->saveTag($tagToSave);
                 }
                 $tagToSave = $tagToFind->first();
                 $tagsArray[] = array($tag, $tagToSave->id);
                 $tagsToSave[] = $tagToSave->id;
             }
             $howtoItem['tags'] = $tagsToSave;
             $saveTags = false;
             if (count($tagsToSave) > 0) {
                 $saveTags = true;
             }
             if ($debugHowTo) {
                 echo '<br />***<br /><br />';
                 foreach ($howtoItem as $key => $value) {
                     echo $key . ': ';
                     if (is_array($howtoItem[$key])) {
                         echo '<br />';
                         foreach ($howtoItem[$key] as $arrayItem) {
                             if (is_array($arrayItem)) {
                                 foreach ($arrayItem as $subArrayItem) {
                                     echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $subArrayItem . '<br />';
                                 }
                             } else {
                                 echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $arrayItem . '<br />';
                             }
                         }
                     } else {
                         echo $howtoItem[$key] . '<br />';
                     }
                 }
             }
             // Save the entry
             if (!$save) {
                 continue;
             }
             $entry = craft()->elements->getCriteria(ElementType::Entry);
             $entry->section = 'investmentAdvisersHowTo';
             $entry->limit = 1;
             $entry->slug = (string) $howtoItem['slug'];
             $existingEntry = $entry->find();
             $entryToSave = new EntryModel();
             if (count($existingEntry > 0)) {
                 foreach ($existingEntry as $existingEntry) {
                     $entryToSave = $existingEntry;
                 }
             }
             // If parent_id == 0, omit setting parent
             if ($importItem->parent_id != 277) {
                 if ($debugHowTo) {
                     echo 'We have a parent entry!<br />';
                 }
                 $parentEntries = craft()->elements->getCriteria(ElementType::Entry);
                 $parentEntries->section = 'investmentAdvisersHowTo';
                 $parentEntries->legacyId = $importItem->parent_id;
                 $parentEntries->limit = 1;
                 $parentEntry = $parentEntries->find();
                 // We are assuming that the source feed outputs the nested categories in order, so the
                 // parent category should already exist. I.e., we don't need to create it if not found.
                 if (count($parentEntry) == 1) {
                     foreach ($parentEntry as $existingParentEntry) {
                         if ($debugHowTo) {
                             echo 'Craft parent ID: ' . $existingParentEntry->id . '<br />';
                         }
                         $entryToSave->parentId = $existingParentEntry->id;
                         $entryToSave->setParent($existingParentEntry);
                     }
                 }
             }
             $entryToSave->sectionId = $sectionId;
             $entryToSave->typeId = $typeId;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             if ($howtoItem['entryStatus'] == 'closed') {
                 $entryToSave->enabled = false;
             }
             $entryToSave->postDate = date('Y-m-d h:m:s', (double) $howtoItem['entryDate']);
             $entryToSave->slug = $howtoItem['slug'];
             $entryToSave->getContent()->setAttributes(array('title' => $howtoItem['entryTitle'], 'legacyId' => $howtoItem['entry_id'], 'pageContent' => $howtoItem['entryContent'], 'isProtected' => 1));
             if ($saveTags) {
                 $entryToSave->getContent()->pageTags = $tagsToSave;
             }
             if (craft()->entries->saveEntry($entryToSave)) {
                 $totalPosts++;
                 $retVal = $totalPosts;
                 continue;
             } else {
                 $retVal = false;
             }
         }
         if ($run_howto_redline) {
             foreach ($howtoXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersHowTo';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 //$entry->slug = $importItem->slug;
                 /*$entry->getContent()->setAttributes(array(
                       'legacyId' => (string)$importItem->id,
                   ));*/
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'How-To entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->redline->redline_item as $item) {
                     $referenceEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $referenceEntry->limit = 1;
                     $referenceEntry->legacyId = (string) $item->reference_item->reference_item_legacy_id;
                     /*$referenceEntry->getContent()->setAttributes(array(
                           'legacyId' => (string)$item->reference_item->reference_item_legacy_id,
                       ));*/
                     $entries = $referenceEntry->find();
                     if (count($entries) == 0) {
                         echo 'Reference Item entry not found! / EE ID: ' . (string) $item->reference_item->reference_item_legacy_id . '<br />';
                         continue;
                     }
                     $existingReferenceEntry = $referenceEntry->first();
                     echo 'Matrix: Reference Entry ID: ' . $existingReferenceEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 48;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 1;
                     $block->getContent()->setAttributes(array('entry' => [$existingReferenceEntry->id], 'annotation' => (string) $item->annotation));
                     craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_howto_greenline) {
             foreach ($howtoXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersHowTo';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'How-To entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->greenline->greenline_item as $item) {
                     $subjectsEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $subjectsEntry->limit = 1;
                     $subjectsEntry->legacyId = (string) $item->legacy_id;
                     $entries = $subjectsEntry->find();
                     if (count($entries) == 0) {
                         echo 'Treatise entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingSubjectsEntry = $subjectsEntry->first();
                     echo 'Matrix: Treatise Entry ID: ' . $existingSubjectsEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 51;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 2;
                     $block->getContent()->setAttributes(array('entry' => [$existingSubjectsEntry->id], 'annotation' => (string) $item->annotation));
                     craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_howto_orangeline) {
             foreach ($howtoXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersHowTo';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'How-To entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->orangeline->orangeline_item as $item) {
                     $lawsrulesEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $lawsrulesEntry->limit = 1;
                     $lawsrulesEntry->legacyId = (string) $item->legacy_id;
                     $entries = $lawsrulesEntry->find();
                     if (count($entries) == 0) {
                         echo 'Laws & Rules entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingLawsRulesEntry = $lawsrulesEntry->first();
                     echo 'Matrix: Laws & Rules Entry ID: ' . $existingLawsRulesEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 57;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 4;
                     $block->getContent()->setAttributes(array('entry' => [$existingLawsRulesEntry->id], 'annotation' => (string) $item->annotation));
                     craft()->matrix->saveBlock($block);
                 }
             }
         }
     }
     if ($run_statute) {
         // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
         $statuteXml = simplexml_load_file('http://40act.craft.dev:8888/statute.xml');
         $sectionId = 6;
         // Visit settings for your Section and check the URL
         $typeId = 6;
         // Visit Entry Types for your Section and check the URL for the Entry Type
         foreach ($statuteXml->entries[0]->item as $importItem) {
             $statuteItem = array();
             // Need to load as legacy ID for parent ID lookups, re-import (though reference re-import was based on slug)
             $statuteItem['entry_id'] = (string) $importItem->id;
             // $entryUrlTitle
             $statuteItem['slug'] = (string) $importItem->slug;
             // $entryDate
             $statuteItem['entryDate'] = $importItem->entry_date;
             // $entryStatus
             $statuteItem['entryStatus'] = (string) $importItem->status;
             // $entryTitle
             $statuteItem['entryTitle'] = (string) $importItem->title;
             // $entryContent – Rich text
             $statuteItem['entryContent'] = $importItem->content;
             // tags
             $tagsToSave = array();
             foreach ($importItem->tags->tag as $tag) {
                 // Need to look up / create tag if it does not exist
                 $tagToFind = craft()->elements->getCriteria(ElementType::Tag);
                 $tagToFind->title = (string) $tag;
                 $tagToFind->limit = 1;
                 $tagToFind->groupId = $tagSetId;
                 $existingTag = $tagToFind->find();
                 if (count($existingTag) == 0) {
                     $tagToSave = new TagModel();
                     $tagToSave->groupId = $tagSetId;
                     $tagToSave->getContent()->setAttributes(array('title' => (string) $tag));
                     craft()->tags->saveTag($tagToSave);
                 }
                 $tagToSave = $tagToFind->first();
                 $tagsArray[] = array($tag, $tagToSave->id);
                 $tagsToSave[] = $tagToSave->id;
             }
             $statuteItem['tags'] = $tagsToSave;
             $saveTags = false;
             if (count($tagsToSave) > 0) {
                 $saveTags = true;
             }
             if ($debugStatute) {
                 echo '<br />***<br /><br />';
                 foreach ($statuteItem as $key => $value) {
                     echo $key . ': ';
                     if (is_array($statuteItem[$key])) {
                         echo '<br />';
                         foreach ($statuteItem[$key] as $arrayItem) {
                             if (is_array($arrayItem)) {
                                 foreach ($arrayItem as $subArrayItem) {
                                     echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $subArrayItem . '<br />';
                                 }
                             } else {
                                 echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $arrayItem . '<br />';
                             }
                         }
                     } else {
                         echo $statuteItem[$key] . '<br />';
                     }
                 }
             }
             // Save the entry
             if (!$save) {
                 continue;
             }
             $entry = craft()->elements->getCriteria(ElementType::Entry);
             $entry->section = 'investmentAdvisersActOf1940Statute';
             $entry->limit = 1;
             $entry->slug = (string) $statuteItem['slug'];
             $existingEntry = $entry->find();
             $entryToSave = new EntryModel();
             if (count($existingEntry > 0)) {
                 foreach ($existingEntry as $existingEntry) {
                     $entryToSave = $existingEntry;
                 }
             }
             // If parent_id == 0, omit setting parent
             if ($importItem->parent_id != 399) {
                 if ($debugStatute) {
                     echo 'We have a parent entry!<br />';
                 }
                 $parentEntries = craft()->elements->getCriteria(ElementType::Entry);
                 $parentEntries->section = 'investmentAdvisersActOf1940Statute';
                 $parentEntries->legacyId = $importItem->parent_id;
                 $parentEntries->limit = 1;
                 $parentEntry = $parentEntries->find();
                 // We are assuming that the source feed outputs the nested categories in order, so the
                 // parent category should already exist. I.e., we don't need to create it if not found.
                 if (count($parentEntry) == 1) {
                     foreach ($parentEntry as $existingParentEntry) {
                         if ($debugStatute) {
                             echo 'Craft parent ID: ' . $existingParentEntry->id . '<br />';
                         }
                         $entryToSave->parentId = $existingParentEntry->id;
                         $entryToSave->setParent($existingParentEntry);
                     }
                 }
             }
             $entryToSave->sectionId = $sectionId;
             $entryToSave->typeId = $typeId;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             if ($statuteItem['entryStatus'] == 'closed') {
                 $entryToSave->enabled = false;
             }
             $entryToSave->postDate = date('Y-m-d h:m:s', (double) $statuteItem['entryDate']);
             $entryToSave->slug = $statuteItem['slug'];
             $entryToSave->getContent()->setAttributes(array('title' => $statuteItem['entryTitle'], 'legacyId' => $statuteItem['entry_id'], 'pageContent' => $statuteItem['entryContent'], 'isProtected' => 0));
             if ($saveTags) {
                 $entryToSave->getContent()->pageTags = $tagsToSave;
             }
             if (craft()->entries->saveEntry($entryToSave)) {
                 $totalPosts++;
                 $retVal = $totalPosts;
                 continue;
             } else {
                 $retVal = false;
             }
         }
         if ($run_statute_redline) {
             foreach ($statuteXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersActOf1940Statute';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 //$entry->slug = $importItem->slug;
                 /*$entry->getContent()->setAttributes(array(
                       'legacyId' => (string)$importItem->id,
                   ));*/
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Statute entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->redline->redline_item as $item) {
                     $referenceEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $referenceEntry->limit = 1;
                     $referenceEntry->legacyId = (string) $item->reference_item->reference_item_legacy_id;
                     /*$referenceEntry->getContent()->setAttributes(array(
                           'legacyId' => (string)$item->reference_item->reference_item_legacy_id,
                       ));*/
                     $entries = $referenceEntry->find();
                     if (count($entries) == 0) {
                         echo 'Reference Item entry not found! / EE ID: ' . (string) $item->reference_item->reference_item_legacy_id . '<br />';
                         continue;
                     }
                     $existingReferenceEntry = $referenceEntry->first();
                     echo 'Matrix: Reference Entry ID: ' . $existingReferenceEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 48;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 1;
                     $block->getContent()->setAttributes(array('entry' => [$existingReferenceEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_statute_greenline) {
             foreach ($statuteXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersActOf1940Statute';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Statute entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->greenline->greenline_item as $item) {
                     $subjectsEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $subjectsEntry->limit = 1;
                     $subjectsEntry->legacyId = (string) $item->legacy_id;
                     $entries = $subjectsEntry->find();
                     if (count($entries) == 0) {
                         echo 'Treatise entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingSubjectsEntry = $subjectsEntry->first();
                     echo 'Matrix: Treatise Entry ID: ' . $existingSubjectsEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 51;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 2;
                     $block->getContent()->setAttributes(array('entry' => [$existingSubjectsEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_statute_blueline) {
             foreach ($statuteXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersActOf1940Statute';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Statute entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->blueline->blueline_item as $item) {
                     $howtoEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $howtoEntry->limit = 1;
                     $howtoEntry->legacyId = (string) $item->legacy_id;
                     $entries = $howtoEntry->find();
                     if (count($entries) == 0) {
                         echo 'How-To entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingHowToEntry = $howtoEntry->first();
                     echo 'Matrix: How-To Entry ID: ' . $existingHowToEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 54;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 3;
                     $block->getContent()->setAttributes(array('entry' => [$existingHowToEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
     }
     if ($run_rules) {
         // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
         $rulesXml = simplexml_load_file('http://40act.craft.dev:8888/rules.xml');
         $sectionId = 7;
         // Visit settings for your Section and check the URL
         $typeId = 7;
         // Visit Entry Types for your Section and check the URL for the Entry Type
         foreach ($rulesXml->entries[0]->item as $importItem) {
             $rulesItem = array();
             // Need to load as legacy ID for parent ID lookups, re-import (though reference re-import was based on slug)
             $rulesItem['entry_id'] = (string) $importItem->id;
             // $entryUrlTitle
             $rulesItem['slug'] = (string) $importItem->slug;
             // $entryDate
             $rulesItem['entryDate'] = $importItem->entry_date;
             // $entryStatus
             $rulesItem['entryStatus'] = (string) $importItem->status;
             // $entryTitle
             $rulesItem['entryTitle'] = (string) $importItem->title;
             // $entryContent – Rich text
             $rulesItem['entryContent'] = $importItem->content;
             // tags
             $tagsToSave = array();
             foreach ($importItem->tags->tag as $tag) {
                 // Need to look up / create tag if it does not exist
                 $tagToFind = craft()->elements->getCriteria(ElementType::Tag);
                 $tagToFind->title = (string) $tag;
                 $tagToFind->limit = 1;
                 $tagToFind->groupId = $tagSetId;
                 $existingTag = $tagToFind->find();
                 if (count($existingTag) == 0) {
                     $tagToSave = new TagModel();
                     $tagToSave->groupId = $tagSetId;
                     $tagToSave->getContent()->setAttributes(array('title' => (string) $tag));
                     craft()->tags->saveTag($tagToSave);
                 }
                 $tagToSave = $tagToFind->first();
                 $tagsArray[] = array($tag, $tagToSave->id);
                 $tagsToSave[] = $tagToSave->id;
             }
             $rulesItem['tags'] = $tagsToSave;
             $saveTags = false;
             if (count($tagsToSave) > 0) {
                 $saveTags = true;
             }
             if ($debugRules) {
                 echo '<br />***<br /><br />';
                 foreach ($rulesItem as $key => $value) {
                     echo $key . ': ';
                     if (is_array($rulesItem[$key])) {
                         echo '<br />';
                         foreach ($rulesItem[$key] as $arrayItem) {
                             if (is_array($arrayItem)) {
                                 foreach ($arrayItem as $subArrayItem) {
                                     echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $subArrayItem . '<br />';
                                 }
                             } else {
                                 echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $arrayItem . '<br />';
                             }
                         }
                     } else {
                         echo $rulesItem[$key] . '<br />';
                     }
                 }
             }
             // Save the entry
             if (!$save) {
                 continue;
             }
             $entry = craft()->elements->getCriteria(ElementType::Entry);
             $entry->section = 'investmentAdvisersActOf1940Rules';
             $entry->limit = 1;
             $entry->slug = (string) $rulesItem['slug'];
             $existingEntry = $entry->find();
             $entryToSave = new EntryModel();
             if (count($existingEntry > 0)) {
                 foreach ($existingEntry as $existingEntry) {
                     $entryToSave = $existingEntry;
                 }
             }
             // If parent_id == 0, omit setting parent
             if ($importItem->parent_id != 401) {
                 if ($debugRules) {
                     echo 'We have a parent entry!<br />';
                 }
                 $parentEntries = craft()->elements->getCriteria(ElementType::Entry);
                 $parentEntries->section = 'investmentAdvisersActOf1940Rules';
                 $parentEntries->legacyId = $importItem->parent_id;
                 $parentEntries->limit = 1;
                 $parentEntry = $parentEntries->find();
                 // We are assuming that the source feed outputs the nested categories in order, so the
                 // parent category should already exist. I.e., we don't need to create it if not found.
                 if (count($parentEntry) == 1) {
                     foreach ($parentEntry as $existingParentEntry) {
                         if ($debugRules) {
                             echo 'Craft parent ID: ' . $existingParentEntry->id . '<br />';
                         }
                         $entryToSave->parentId = $existingParentEntry->id;
                         $entryToSave->setParent($existingParentEntry);
                     }
                 }
             }
             $entryToSave->sectionId = $sectionId;
             $entryToSave->typeId = $typeId;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             if ($rulesItem['entryStatus'] == 'closed') {
                 $entryToSave->enabled = false;
             }
             $entryToSave->postDate = date('Y-m-d h:m:s', (double) $rulesItem['entryDate']);
             $entryToSave->slug = $rulesItem['slug'];
             $entryToSave->getContent()->setAttributes(array('title' => $rulesItem['entryTitle'], 'legacyId' => $rulesItem['entry_id'], 'pageContent' => $rulesItem['entryContent'], 'isProtected' => 0));
             if ($saveTags) {
                 $entryToSave->getContent()->pageTags = $tagsToSave;
             }
             if (craft()->entries->saveEntry($entryToSave)) {
                 $totalPosts++;
                 $retVal = $totalPosts;
                 continue;
             } else {
                 $retVal = false;
             }
         }
         if ($run_rules_redline) {
             foreach ($rulesXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersActOf1940Rules';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 //$entry->slug = $importItem->slug;
                 /*$entry->getContent()->setAttributes(array(
                       'legacyId' => (string)$importItem->id,
                   ));*/
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Rules entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->redline->redline_item as $item) {
                     $referenceEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $referenceEntry->limit = 1;
                     $referenceEntry->legacyId = (string) $item->reference_item->reference_item_legacy_id;
                     /*$referenceEntry->getContent()->setAttributes(array(
                           'legacyId' => (string)$item->reference_item->reference_item_legacy_id,
                       ));*/
                     $entries = $referenceEntry->find();
                     if (count($entries) == 0) {
                         echo 'Reference Item entry not found! / EE ID: ' . (string) $item->reference_item->reference_item_legacy_id . '<br />';
                         continue;
                     }
                     $existingReferenceEntry = $referenceEntry->first();
                     echo 'Matrix: Reference Entry ID: ' . $existingReferenceEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 48;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 1;
                     $block->getContent()->setAttributes(array('entry' => [$existingReferenceEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_rules_greenline) {
             foreach ($rulesXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersActOf1940Rules';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Rules entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->greenline->greenline_item as $item) {
                     $subjectsEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $subjectsEntry->limit = 1;
                     $subjectsEntry->legacyId = (string) $item->legacy_id;
                     $entries = $subjectsEntry->find();
                     if (count($entries) == 0) {
                         echo 'Treatise entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingSubjectsEntry = $subjectsEntry->first();
                     echo 'Matrix: Treatise Entry ID: ' . $existingSubjectsEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 51;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 2;
                     $block->getContent()->setAttributes(array('entry' => [$existingSubjectsEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_rules_blueline) {
             foreach ($rulesXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'investmentAdvisersActOf1940Rules';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Rules entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->blueline->blueline_item as $item) {
                     $howtoEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $howtoEntry->limit = 1;
                     $howtoEntry->legacyId = (string) $item->legacy_id;
                     $entries = $howtoEntry->find();
                     if (count($entries) == 0) {
                         echo 'How-To entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingHowToEntry = $howtoEntry->first();
                     echo 'Matrix: How-To Entry ID: ' . $existingHowToEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 54;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 3;
                     $block->getContent()->setAttributes(array('entry' => [$existingHowToEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
     }
     if ($run_other_rules) {
         // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
         $otherRulesXml = simplexml_load_file('http://40act.craft.dev:8888/other-rules.xml');
         $sectionId = 8;
         // Visit settings for your Section and check the URL
         $typeId = 8;
         // Visit Entry Types for your Section and check the URL for the Entry Type
         foreach ($otherRulesXml->entries[0]->item as $importItem) {
             $rulesItem = array();
             // Need to load as legacy ID for parent ID lookups, re-import (though reference re-import was based on slug)
             $rulesItem['entry_id'] = (string) $importItem->id;
             // $entryUrlTitle
             $rulesItem['slug'] = (string) $importItem->slug;
             // $entryDate
             $rulesItem['entryDate'] = $importItem->entry_date;
             // $entryStatus
             $rulesItem['entryStatus'] = (string) $importItem->status;
             // $entryTitle
             $rulesItem['entryTitle'] = (string) $importItem->title;
             // $entryContent – Rich text
             $rulesItem['entryContent'] = $importItem->content;
             // tags
             $tagsToSave = array();
             foreach ($importItem->tags->tag as $tag) {
                 // Need to look up / create tag if it does not exist
                 $tagToFind = craft()->elements->getCriteria(ElementType::Tag);
                 $tagToFind->title = (string) $tag;
                 $tagToFind->limit = 1;
                 $tagToFind->groupId = $tagSetId;
                 $existingTag = $tagToFind->find();
                 if (count($existingTag) == 0) {
                     $tagToSave = new TagModel();
                     $tagToSave->groupId = $tagSetId;
                     $tagToSave->getContent()->setAttributes(array('title' => (string) $tag));
                     craft()->tags->saveTag($tagToSave);
                 }
                 $tagToSave = $tagToFind->first();
                 $tagsArray[] = array($tag, $tagToSave->id);
                 $tagsToSave[] = $tagToSave->id;
             }
             $rulesItem['tags'] = $tagsToSave;
             $saveTags = false;
             if (count($tagsToSave) > 0) {
                 $saveTags = true;
             }
             if ($debugOtherRules) {
                 echo '<br />***<br /><br />';
                 foreach ($rulesItem as $key => $value) {
                     echo $key . ': ';
                     if (is_array($rulesItem[$key])) {
                         echo '<br />';
                         foreach ($rulesItem[$key] as $arrayItem) {
                             if (is_array($arrayItem)) {
                                 foreach ($arrayItem as $subArrayItem) {
                                     echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $subArrayItem . '<br />';
                                 }
                             } else {
                                 echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $arrayItem . '<br />';
                             }
                         }
                     } else {
                         echo $rulesItem[$key] . '<br />';
                     }
                 }
             }
             // Save the entry
             if (!$save) {
                 continue;
             }
             $entry = craft()->elements->getCriteria(ElementType::Entry);
             $entry->section = 'otherLawsRules';
             $entry->limit = 1;
             $entry->slug = (string) $rulesItem['slug'];
             $existingEntry = $entry->find();
             $entryToSave = new EntryModel();
             if (count($existingEntry > 0)) {
                 foreach ($existingEntry as $existingEntry) {
                     $entryToSave = $existingEntry;
                 }
             }
             // If parent_id == 0, omit setting parent
             if ($importItem->parent_id != 401) {
                 if ($debugOtherRules) {
                     echo 'We have a parent entry!<br />';
                 }
                 $parentEntries = craft()->elements->getCriteria(ElementType::Entry);
                 $parentEntries->section = 'otherLawsRules';
                 $parentEntries->legacyId = $importItem->parent_id;
                 $parentEntries->limit = 1;
                 $parentEntry = $parentEntries->find();
                 // We are assuming that the source feed outputs the nested categories in order, so the
                 // parent category should already exist. I.e., we don't need to create it if not found.
                 if (count($parentEntry) == 1) {
                     foreach ($parentEntry as $existingParentEntry) {
                         if ($debugOtherRules) {
                             echo 'Craft parent ID: ' . $existingParentEntry->id . '<br />';
                         }
                         $entryToSave->parentId = $existingParentEntry->id;
                         $entryToSave->setParent($existingParentEntry);
                     }
                 }
             }
             $entryToSave->sectionId = $sectionId;
             $entryToSave->typeId = $typeId;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             if ($rulesItem['entryStatus'] == 'closed') {
                 $entryToSave->enabled = false;
             }
             $entryToSave->postDate = date('Y-m-d h:m:s', (double) $rulesItem['entryDate']);
             $entryToSave->slug = $rulesItem['slug'];
             $entryToSave->getContent()->setAttributes(array('title' => $rulesItem['entryTitle'], 'legacyId' => $rulesItem['entry_id'], 'pageContent' => $rulesItem['entryContent'], 'isProtected' => 0));
             if ($saveTags) {
                 $entryToSave->getContent()->pageTags = $tagsToSave;
             }
             if (craft()->entries->saveEntry($entryToSave)) {
                 $totalPosts++;
                 $retVal = $totalPosts;
                 continue;
             } else {
                 $retVal = false;
             }
         }
         if ($run_other_rules_redline) {
             foreach ($otherRulesXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'otherLawsRules';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 //$entry->slug = $importItem->slug;
                 /*$entry->getContent()->setAttributes(array(
                       'legacyId' => (string)$importItem->id,
                   ));*/
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Other Rules entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->redline->redline_item as $item) {
                     $referenceEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $referenceEntry->limit = 1;
                     $referenceEntry->legacyId = (string) $item->reference_item->reference_item_legacy_id;
                     /*$referenceEntry->getContent()->setAttributes(array(
                           'legacyId' => (string)$item->reference_item->reference_item_legacy_id,
                       ));*/
                     $entries = $referenceEntry->find();
                     if (count($entries) == 0) {
                         echo 'Reference Item entry not found! / EE ID: ' . (string) $item->reference_item->reference_item_legacy_id . '<br />';
                         continue;
                     }
                     $existingReferenceEntry = $referenceEntry->first();
                     echo 'Matrix: Reference Entry ID: ' . $existingReferenceEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 48;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 1;
                     $block->getContent()->setAttributes(array('entry' => [$existingReferenceEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_other_rules_greenline) {
             foreach ($otherRulesXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'otherLawsRules';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Other Rules entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->greenline->greenline_item as $item) {
                     $subjectsEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $subjectsEntry->limit = 1;
                     $subjectsEntry->legacyId = (string) $item->legacy_id;
                     $entries = $subjectsEntry->find();
                     if (count($entries) == 0) {
                         echo 'Treatise entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingSubjectsEntry = $subjectsEntry->first();
                     echo 'Matrix: Treatise Entry ID: ' . $existingSubjectsEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 51;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 2;
                     $block->getContent()->setAttributes(array('entry' => [$existingSubjectsEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
         if ($run_other_rules_blueline) {
             foreach ($otherRulesXml->entries[0]->item as $importItem) {
                 $entry = craft()->elements->getCriteria(ElementType::Entry);
                 $entry->section = 'otherLawsRules';
                 $entry->limit = 1;
                 $entry->legacyId = (string) $importItem->id;
                 echo '<br /><br />*****<br />';
                 $entries = $entry->find();
                 if (count($entries) == 0) {
                     echo 'Other Rules entry not found! / EE ID: ' . $importItem->id . '<br />';
                     continue;
                 }
                 echo (string) $importItem->id . '<br />';
                 $existingEntry = $entry->first();
                 echo 'Matrix: Entry ID: ' . $existingEntry->id . '<br />';
                 foreach ($importItem->blueline->blueline_item as $item) {
                     $howtoEntry = craft()->elements->getCriteria(ElementType::Entry);
                     $howtoEntry->limit = 1;
                     $howtoEntry->legacyId = (string) $item->legacy_id;
                     $entries = $howtoEntry->find();
                     if (count($entries) == 0) {
                         echo 'How-To entry not found! / EE ID: ' . (string) $item->legacy_id . '<br />';
                         continue;
                     }
                     $existingHowToEntry = $howtoEntry->first();
                     echo 'Matrix: How-To Entry ID: ' . $existingHowToEntry->id . '<br />';
                     $block = new MatrixBlockModel();
                     $block->fieldId = 54;
                     $block->ownerId = $existingEntry->id;
                     $block->typeId = 3;
                     $block->getContent()->setAttributes(array('entry' => [$existingHowToEntry->id], 'annotation' => (string) $item->annotation));
                     //craft()->matrix->saveBlock($block);
                 }
             }
         }
     }
     if ($run_news) {
         // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
         $newsXml = simplexml_load_file('http://40act.craft.dev:8888/news.xml');
         // Replace with Reference Materials feed
         $sectionId = 2;
         // Visit settings for your Section and check the URL
         $typeId = 2;
         // Visit Entry Types for your Section and check the URL for the Entry Type
         foreach ($newsXml->news[0]->article as $importItem) {
             // Note that the URL field has not been used on the EE site, so we're not going to import the URL entry type (10)
             $newsItem = array();
             $newsItem['entry_id'] = (string) $importItem->id;
             $newsItem['slug'] = (string) $importItem->slug;
             $newsItem['entryDate'] = $importItem->entry_date;
             $newsItem['entryStatus'] = (string) $importItem->status;
             $newsItem['entryTitle'] = (string) $importItem->title;
             $newsItem['newsUrl'] = (string) $importItem->url;
             $newsItem['newsBlurb'] = (string) $importItem->blurb;
             $newsItem['newsArticle'] = (string) $importItem->article;
             $tagsArray = array();
             $tagsToSave = array();
             foreach ($importItem->tags->tag as $tag) {
                 // Need to look up / create tag if it does not exist
                 $tagToFind = craft()->elements->getCriteria(ElementType::Tag);
                 $tagToFind->title = (string) $tag;
                 $tagToFind->limit = 1;
                 $tagToFind->groupId = $tagSetId;
                 $existingTag = $tagToFind->find();
                 if (count($existingTag) == 0) {
                     $tagToSave = new TagModel();
                     $tagToSave->groupId = $tagSetId;
                     $tagToSave->getContent()->setAttributes(array('title' => (string) $tag));
                     craft()->tags->saveTag($tagToSave);
                 }
                 $tagToSave = $tagToFind->first();
                 $tagsArray[] = array($tag, $tagToSave->id);
                 $tagsToSave[] = $tagToSave->id;
             }
             $newsItem['tags'] = $tagsToSave;
             $saveTags = false;
             if (count($tagsToSave) > 0) {
                 $saveTags = true;
             }
             if ($debugNews) {
                 echo '<br />***<br /><br />';
                 foreach ($newsItem as $key => $value) {
                     echo $key . ': ';
                     if (is_array($newsItem[$key])) {
                         echo '<br />';
                         foreach ($newsItem[$key] as $arrayItem) {
                             if (is_array($arrayItem)) {
                                 foreach ($arrayItem as $subArrayItem) {
                                     echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $subArrayItem . '<br />';
                                 }
                             } else {
                                 echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $arrayItem . '<br />';
                             }
                         }
                     } else {
                         echo $newsItem[$key] . '<br />';
                     }
                 }
             }
             // Default page protected to Yes
             // Save the entry
             if (!$save) {
                 continue;
             }
             $entry = craft()->elements->getCriteria(ElementType::Entry);
             $entry->section = 'news';
             $entry->limit = 1;
             $entry->slug = (string) $newsItem['slug'];
             $existingEntry = $entry->find();
             $entryToSave = new EntryModel();
             if (count($existingEntry > 0)) {
                 foreach ($existingEntry as $existingEntry) {
                     $entryToSave = $existingEntry;
                 }
             }
             $entryToSave->sectionId = $sectionId;
             $entryToSave->typeId = $typeId;
             $entryToSave->authorId = 1;
             $entryToSave->enabled = true;
             if ($newsItem['entryStatus'] == 'closed') {
                 $entryToSave->enabled = false;
             }
             $entryToSave->postDate = date('Y-m-d h:m:s', (double) $newsItem['entryDate']);
             $entryToSave->slug = $newsItem['slug'];
             $entryToSave->getContent()->setAttributes(array('title' => $newsItem['entryTitle'], 'newsBlurb' => $newsItem['newsBlurb'], 'newsUrl' => $newsItem['newsUrl'], 'newsArticle' => $newsItem['newsArticle'], 'legacyId' => $newsItem['entry_id']));
             if ($saveTags) {
                 $entryToSave->getContent()->tags = $tagsToSave;
             }
             if (craft()->entries->saveEntry($entryToSave)) {
                 $totalPosts++;
                 $retVal = $totalPosts;
                 continue;
             } else {
                 $retVal = false;
             }
         }
     }
     if ($debug) {
         exit;
     }
     return $retVal;
 }
 /**
  * Saves tag from wordpress
  *
  * @param string $name Title for new/existing category
  * @param string $tagGroupId Tag group id for saving tags
  *
  * @return integer Id for tag.
  */
 protected function _importTag($name, $tagGroupId)
 {
     // Check to see if category exists
     $criteria = craft()->elements->getCriteria(ElementType::Tag);
     $criteria->groupId = $tagGroupId;
     $criteria->limit = null;
     $findTags = $criteria->find();
     $match = false;
     foreach ($findTags as $findTag) {
         if ($findTag->name == $name) {
             return $findTag->id;
         }
     }
     // Save the tag
     $tag = new TagModel();
     $tag->groupId = $tagGroupId;
     $tag->getContent()->title = $name;
     if (!craft()->tags->saveTag($tag)) {
         Craft::log('Couldn’t save the tag "' . $name . '"', LogLevel::Warning, true, '_importTag', 'InstaBlog');
         return false;
     } else {
         return $tag->id;
     }
 }
Esempio n. 24
0
 /**
  * Edit Tag form.
  */
 public function SettingsController_EditTag_Create($Sender)
 {
     $Sender->Permission('Garden.Settings.Manage');
     $Sender->Title(T('Edit Tag'));
     $Sender->AddSideMenu('settings/tagging');
     $TagID = GetValue(0, $Sender->RequestArgs);
     $TagModel = new TagModel();
     $Sender->Tag = $TagModel->GetWhere(array('TagID' => $TagID))->FirstRow();
     // Set the model on the form.
     $Sender->Form->SetModel($TagModel);
     // Make sure the form knows which item we are editing.
     $Sender->Form->AddHidden('TagID', $TagID);
     if (!$Sender->Form->AuthenticatedPostBack()) {
         $Sender->Form->SetData($Sender->Tag);
     } else {
         // Make sure the tag is valid
         $Tag = $Sender->Form->GetFormValue('Name');
         if (!TagModel::ValidateTag($Tag)) {
             $Sender->Form->AddError('@' . T('ValidateTag', 'Tags cannot contain spaces.'));
         }
         // Make sure that the tag name is not already in use.
         if ($TagModel->GetWhere(array('TagID <>' => $TagID, 'Name' => $Tag))->NumRows() > 0) {
             $Sender->SetData('MergeTagVisible', TRUE);
             if (!$Sender->Form->GetFormValue('MergeTag')) {
                 $Sender->Form->AddError('The specified tag name is already in use.');
             }
         }
         if ($Sender->Form->Save()) {
             $Sender->InformMessage(T('Your changes have been saved.'));
         }
     }
     $Sender->Render('EditTag', '', 'plugins/Tagging');
 }
Esempio n. 25
0
 public function getAll($where = "", $order = "")
 {
     $obj = new TagModel();
     return $obj->getAll($where);
 }
Esempio n. 26
0
 public function updateInfo($para)
 {
     try {
         if ($this->validateUpdateInfo($para)) {
             $countryBO = $this->get($para->term_taxonomy_id);
             if ($countryBO != NULL) {
                 if (isset($para->name)) {
                     $countryBO->name = $para->name;
                 }
                 if (isset($para->slug)) {
                     $countryBO->slug = $para->slug;
                 }
                 if (isset($para->description)) {
                     $countryBO->description = $para->description;
                 }
                 if (isset($para->parent)) {
                     $countryBO->parent = $para->parent;
                 } else {
                     $countryBO->parent = 0;
                 }
                 if (isset($para->image_weather_delete_list)) {
                     $countryBO->image_weather_delete_list = $para->image_weather_delete_list;
                 }
                 if (isset($para->image_weathers)) {
                     $countryBO->image_weathers_upload = $para->image_weathers;
                 }
                 $this->db->beginTransaction();
                 if ($this->update($countryBO)) {
                     if (isset($countryBO->overview) || isset($countryBO->history) || isset($para->overview) || isset($para->history) || isset($countryBO->weather) || isset($countryBO->passport_visa) || isset($para->weather) || isset($para->passport_visa) || isset($countryBO->currency) || isset($countryBO->phone_internet_service) || isset($para->currency) || isset($para->phone_internet_service) || isset($countryBO->transportation) || isset($countryBO->food_drink) || isset($para->transportation) || isset($para->food_drink) || isset($countryBO->public_holiday) || isset($countryBO->predeparture_check_list) || isset($para->public_holiday) || isset($para->predeparture_check_list)) {
                         if (isset($para->overview)) {
                             $countryBO->overview = $para->overview;
                         }
                         if (isset($para->history)) {
                             $countryBO->history = $para->history;
                         }
                         if (isset($para->weather)) {
                             $countryBO->weather = $para->weather;
                         }
                         if (isset($para->passport_visa)) {
                             $countryBO->passport_visa = $para->passport_visa;
                         }
                         if (isset($para->currency)) {
                             $countryBO->currency = $para->currency;
                         }
                         if (isset($para->phone_internet_service)) {
                             $countryBO->phone_internet_service = $para->phone_internet_service;
                         }
                         if (isset($para->transportation)) {
                             $countryBO->transportation = $para->transportation;
                         }
                         if (isset($para->food_drink)) {
                             $countryBO->food_drink = $para->food_drink;
                         }
                         if (isset($para->public_holiday)) {
                             $countryBO->public_holiday = $para->public_holiday;
                         }
                         if (isset($para->public_holiday)) {
                             $countryBO->public_holiday = $para->public_holiday;
                         }
                         if (isset($para->predeparture_check_list)) {
                             $countryBO->predeparture_check_list = $para->predeparture_check_list;
                         }
                         $this->updateContent($countryBO);
                         if (isset($para->tag_array) || isset($countryBO->tag_list)) {
                             Model::autoloadModel('tag');
                             $tagModel = new TagModel($this->db);
                             Model::autoloadModel('taxonomy');
                             $taxonomyModel = new TaxonomyModel($this->db);
                             if (!isset($para->tag_array) || count($para->tag_array) == 0) {
                                 foreach ($countryBO->tag_list as $tag) {
                                     $tagModel->deleteRelationship($countryBO->postBO->ID, $tag->term_taxonomy_id);
                                 }
                             } elseif (!isset($countryBO->tag_list) || count($countryBO->tag_list) == 0) {
                                 if (count($para->tag_array) > 0) {
                                     $tag_id_array = $tagModel->addTagArray($para->tag_array);
                                     for ($i = 0; $i < count($tag_id_array); $i++) {
                                         $taxonomyModel->addRelationshipToDatabase($countryBO->postBO->ID, $tag_id_array[$i]);
                                     }
                                 }
                             } elseif (isset($para->tag_array) && isset($countryBO->tag_list) && count($para->tag_array) > 0 && count($countryBO->tag_list) > 0) {
                                 $tags_old_array = array();
                                 foreach ($countryBO->tag_list as $tag_old) {
                                     $tags_old_array[] = $tag_old->name;
                                 }
                                 $tags_new_array = array();
                                 for ($i = 0; $i < count($para->tag_array); $i++) {
                                     if (!in_array($para->tag_array[$i], $tags_old_array)) {
                                         $tags_new_array[] = $para->tag_array[$i];
                                     }
                                 }
                                 if (count($tags_new_array) > 0) {
                                     $tag_id_new_array = $tagModel->addTagArray($tags_new_array);
                                     for ($i = 0; $i < count($tag_id_new_array); $i++) {
                                         $taxonomyModel->addRelationshipToDatabase($countryBO->postBO->ID, $tag_id_new_array[$i]);
                                     }
                                 }
                                 $tags_delete_array = array();
                                 for ($i = 0; $i < count($countryBO->tag_list); $i++) {
                                     if (!in_array($countryBO->tag_list[$i]->name, $para->tag_array)) {
                                         $tags_delete_array[] = $countryBO->tag_list[$i];
                                     }
                                 }
                                 if (count($tags_delete_array) > 0) {
                                     foreach ($tags_delete_array as $tag) {
                                         $tagModel->deleteRelationship($countryBO->postBO->ID, $tag->term_taxonomy_id);
                                     }
                                 }
                             }
                         }
                     }
                     $this->db->commit();
                     $_SESSION["fb_success"][] = UPDATE_COUNTRY_SUCCESS;
                     return TRUE;
                 } else {
                     $this->db->rollBack();
                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_COUNTRY;
                 }
             }
         }
     } catch (Exception $e) {
         $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_COUNTRY;
     }
     return FALSE;
 }
Esempio n. 27
0
 /**
  * Prepare fields for fieldtypes.
  *
  * @param string &$data
  * @param string $handle
  *
  * @return mixed
  */
 public function prepForFieldType(&$data, $handle)
 {
     // Fresh up $data
     $data = StringHelper::convertToUTF8($data);
     $data = trim($data);
     // Get field info
     $field = craft()->fields->getFieldByHandle($handle);
     // If it's a field ofcourse
     if (!is_null($field)) {
         // For some fieldtypes the're special rules
         switch ($field->type) {
             case ImportModel::FieldTypeEntries:
                 // No newlines allowed
                 $data = str_replace("\n", '', $data);
                 $data = str_replace("\r", '', $data);
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get source id's for connecting
                     $sectionIds = array();
                     $sources = $settings->sources;
                     if (is_array($sources)) {
                         foreach ($sources as $source) {
                             list($type, $id) = explode(':', $source);
                             $sectionIds[] = $id;
                         }
                     }
                     // Find matching element in sections
                     $criteria = craft()->elements->getCriteria(ElementType::Entry);
                     $criteria->sectionId = $sectionIds;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Assets at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Search
                         $criteria->search = $query;
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeCategories:
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get source id
                     $source = $settings->source;
                     list($type, $id) = explode(':', $source);
                     // Get category data
                     $category = new CategoryModel();
                     $category->groupId = $id;
                     // This we append before the slugified path
                     $categoryUrl = str_replace('{slug}', '', $category->getUrlFormat());
                     // Find matching elements in categories
                     $criteria = craft()->elements->getCriteria(ElementType::Category);
                     $criteria->groupId = $id;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Categories at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Find matching element by URI (dirty, not all categories have URI's)
                         $criteria->uri = $categoryUrl . $this->slugify($query);
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeAssets:
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get folder id's for connecting
                     $folderIds = array();
                     $folders = $settings->sources;
                     if (is_array($folders)) {
                         foreach ($folders as $folder) {
                             list($type, $id) = explode(':', $folder);
                             $folderIds[] = $id;
                         }
                     }
                     // Find matching element in folders
                     $criteria = craft()->elements->getCriteria(ElementType::Asset);
                     $criteria->folderId = $folderIds;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Assets at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Search
                         $criteria->search = $query;
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeUsers:
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get group id's for connecting
                     $groupIds = array();
                     $sources = $settings->sources;
                     if (is_array($sources)) {
                         foreach ($sources as $source) {
                             list($type, $id) = explode(':', $source);
                             $groupIds[] = $id;
                         }
                     }
                     // Find matching element in sources
                     $criteria = craft()->elements->getCriteria(ElementType::User);
                     $criteria->groupId = $groupIds;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Users at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Search
                         $criteria->search = $query;
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeTags:
                 // Get field settings
                 $settings = $field->getFieldType()->getSettings();
                 // Get tag group id
                 $source = $settings->getAttribute('source');
                 list($type, $groupId) = explode(':', $source);
                 $tags = ArrayHelper::stringToArray($data);
                 $data = array();
                 foreach ($tags as $tag) {
                     // Find existing tag
                     $criteria = craft()->elements->getCriteria(ElementType::Tag);
                     $criteria->title = $tag;
                     $criteria->groupId = $groupId;
                     if (!$criteria->total()) {
                         // Create tag if one doesn't already exist
                         $newtag = new TagModel();
                         $newtag->getContent()->title = $tag;
                         $newtag->groupId = $groupId;
                         // Save tag
                         if (craft()->tags->saveTag($newtag)) {
                             $tagArray = array($newtag->id);
                         }
                     } else {
                         $tagArray = $criteria->ids();
                     }
                     // Add tags to data array
                     $data = array_merge($data, $tagArray);
                 }
                 break;
             case ImportModel::FieldTypeNumber:
                 // Parse as number
                 $data = LocalizationHelper::normalizeNumber($data);
                 // Parse as float
                 $data = floatval($data);
                 break;
             case ImportModel::FieldTypeDate:
                 // Parse date from string
                 $data = DateTimeHelper::formatTimeForDb(DateTimeHelper::fromString($data, craft()->timezone));
                 break;
             case ImportModel::FieldTypeRadioButtons:
             case ImportModel::FieldTypeDropdown:
                 //get field settings
                 $settings = $field->getFieldType()->getSettings();
                 //get field options
                 $options = $settings->getAttribute('options');
                 // find matching option label
                 $labelSelected = false;
                 foreach ($options as $option) {
                     if ($labelSelected) {
                         continue;
                     }
                     if ($data == $option['label']) {
                         $data = $option['value'];
                         //stop looking after first match
                         $labelSelected = true;
                     }
                 }
                 break;
             case ImportModel::FieldTypeCheckboxes:
             case ImportModel::FieldTypeMultiSelect:
                 // Convert to array
                 $data = ArrayHelper::stringToArray($data);
                 break;
             case ImportModel::FieldTypeLightSwitch:
                 // Convert yes/no values to boolean
                 switch ($data) {
                     case Craft::t('Yes'):
                         $data = true;
                         break;
                     case Craft::t('No'):
                         $data = false;
                         break;
                 }
                 break;
         }
     }
     return $data;
 }
Esempio n. 28
0
 public function updateInfo($para)
 {
     try {
         if ($this->validateUpdateInfo($para)) {
             $attractionBO = $this->get($para->term_taxonomy_id);
             if ($attractionBO != NULL) {
                 if (isset($para->name)) {
                     $attractionBO->name = $para->name;
                 }
                 if (isset($para->slug)) {
                     $attractionBO->slug = $para->slug;
                 }
                 if (isset($para->description)) {
                     $attractionBO->description = $para->description;
                 }
                 if (isset($para->image_delete_list)) {
                     $attractionBO->image_delete_list = $para->image_delete_list;
                 }
                 if (isset($para->images)) {
                     $attractionBO->images_upload = $para->images;
                 }
                 if (isset($para->parent)) {
                     $attractionBO->parent = $para->parent;
                 }
                 $this->db->beginTransaction();
                 if ($this->update($attractionBO)) {
                     if (isset($para->country)) {
                         if (!isset($attractionBO->country)) {
                             $attractionBO->country = $para->country;
                             $this->addMetaInfoToDatabase($attractionBO->term_id, "country", $attractionBO->country);
                         } else {
                             if ($attractionBO->country != $para->country) {
                                 $attractionBO->country = $para->country;
                                 $this->updateMetaInfoToDatabase($attractionBO->term_id, "country", $attractionBO->country);
                             }
                         }
                     }
                     if (isset($para->city)) {
                         if (!isset($attractionBO->city)) {
                             $attractionBO->city = $para->city;
                             $this->addMetaInfoToDatabase($attractionBO->term_id, "city", $attractionBO->city);
                         } else {
                             if ($attractionBO->city != $para->city) {
                                 $attractionBO->city = $para->city;
                                 $this->updateMetaInfoToDatabase($attractionBO->term_id, "city", $attractionBO->city);
                             }
                         }
                     }
                     if (isset($para->destination)) {
                         if (!isset($attractionBO->destination)) {
                             $attractionBO->destination = $para->destination;
                             $this->addMetaInfoToDatabase($attractionBO->term_id, "destination", $attractionBO->destination);
                         } else {
                             if ($attractionBO->destination != $para->destination) {
                                 $attractionBO->destination = $para->destination;
                                 $this->updateMetaInfoToDatabase($attractionBO->term_id, "destination", $attractionBO->destination);
                             }
                         }
                     }
                     if (isset($para->current_rating)) {
                         if (!isset($attractionBO->current_rating)) {
                             $attractionBO->current_rating = $para->current_rating;
                             $this->addMetaInfoToDatabase($attractionBO->term_id, "current_rating", $attractionBO->current_rating);
                         } else {
                             if ($attractionBO->current_rating != $para->current_rating) {
                                 $attractionBO->current_rating = $para->current_rating;
                                 $this->updateMetaInfoToDatabase($attractionBO->term_id, "current_rating", $attractionBO->current_rating);
                             }
                         }
                     }
                     if (isset($para->vote_times)) {
                         if (!isset($attractionBO->vote_times)) {
                             $attractionBO->vote_times = $para->vote_times;
                             $this->addMetaInfoToDatabase($attractionBO->term_id, "vote_times", $attractionBO->vote_times) == NULL;
                         } else {
                             if ($attractionBO->vote_times != $para->vote_times) {
                                 $attractionBO->vote_times = $para->vote_times;
                                 $this->updateMetaInfoToDatabase($attractionBO->term_id, "vote_times", $attractionBO->vote_times);
                             }
                         }
                     }
                     if (isset($attractionBO->post_content_1) || isset($attractionBO->post_content_2) || isset($para->post_content_1) || isset($para->post_content_2)) {
                         if (isset($para->post_content_1)) {
                             $attractionBO->post_content_1 = $para->post_content_1;
                         }
                         if (isset($para->post_content_2)) {
                             $attractionBO->post_content_2 = $para->post_content_2;
                         }
                         $this->updateContent($attractionBO);
                         if (isset($para->tag_array) || isset($attractionBO->tag_list)) {
                             Model::autoloadModel('tag');
                             $tagModel = new TagModel($this->db);
                             Model::autoloadModel('taxonomy');
                             $taxonomyModel = new TaxonomyModel($this->db);
                             if (!isset($para->tag_array) || count($para->tag_array) == 0) {
                                 foreach ($attractionBO->tag_list as $tag) {
                                     $tagModel->deleteRelationship($attractionBO->postBO->ID, $tag->term_taxonomy_id);
                                 }
                             } elseif (!isset($attractionBO->tag_list) || count($attractionBO->tag_list) == 0) {
                                 if (count($para->tag_array) > 0) {
                                     $tag_id_array = $tagModel->addTagArray($para->tag_array);
                                     for ($i = 0; $i < count($tag_id_array); $i++) {
                                         $taxonomyModel->addRelationshipToDatabase($attractionBO->postBO->ID, $tag_id_array[$i]);
                                     }
                                 }
                             } elseif (isset($para->tag_array) && isset($attractionBO->tag_list) && count($para->tag_array) > 0 && count($attractionBO->tag_list) > 0) {
                                 $tags_old_array = array();
                                 foreach ($attractionBO->tag_list as $tag_old) {
                                     $tags_old_array[] = $tag_old->name;
                                 }
                                 $tags_new_array = array();
                                 for ($i = 0; $i < count($para->tag_array); $i++) {
                                     if (!in_array($para->tag_array[$i], $tags_old_array)) {
                                         $tags_new_array[] = $para->tag_array[$i];
                                     }
                                 }
                                 if (count($tags_new_array) > 0) {
                                     $tag_id_new_array = $tagModel->addTagArray($tags_new_array);
                                     for ($i = 0; $i < count($tag_id_new_array); $i++) {
                                         $taxonomyModel->addRelationshipToDatabase($attractionBO->postBO->ID, $tag_id_new_array[$i]);
                                     }
                                 }
                                 $tags_delete_array = array();
                                 for ($i = 0; $i < count($attractionBO->tag_list); $i++) {
                                     if (!in_array($attractionBO->tag_list[$i]->name, $para->tag_array)) {
                                         $tags_delete_array[] = $attractionBO->tag_list[$i];
                                     }
                                 }
                                 if (count($tags_delete_array) > 0) {
                                     foreach ($tags_delete_array as $tag) {
                                         $tagModel->deleteRelationship($attractionBO->postBO->ID, $tag->term_taxonomy_id);
                                     }
                                 }
                             }
                         }
                     }
                     $this->db->commit();
                     $_SESSION["fb_success"][] = UPDATE_ATTRACTION_SUCCESS;
                     return TRUE;
                 } else {
                     $this->db->rollBack();
                     $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_ATTRACTION;
                 }
             }
         }
     } catch (Exception $e) {
         $_SESSION["fb_error"][] = ERROR_UPDATE_INFO_ATTRACTION;
     }
     return FALSE;
 }
Esempio n. 29
0
 /**
  * Populates an element model based on a query result.
  *
  * @param array $row
  * @return array
  */
 public function populateElementModel($row)
 {
     return TagModel::populateModel($row);
 }
Esempio n. 30
0
 /**
  *
  *
  * @param $discussion_id
  * @param $tags
  * @param array $types
  * @param int $category_id
  * @param string $new_type
  * @throws Exception
  */
 public function saveDiscussion($discussion_id, $tags, $types = array(''), $category_id = 0, $new_type = '')
 {
     // First grab all of the current tags.
     $all_tags = $current_tags = $this->getDiscussionTags($discussion_id, TagModel::IX_TAGID);
     // Put all the default tag types in the types if necessary.
     if (in_array('', $types)) {
         $types = array_merge($types, array_keys($this->defaultTypes()));
         $types = array_unique($types);
     }
     // Remove the types from the current tags that we don't need anymore.
     $current_tags = array_filter($current_tags, function ($row) use($types) {
         if (in_array($row['Type'], $types)) {
             return true;
         }
         return false;
     });
     // Turn the tags into a nice array.
     if (is_string($tags)) {
         $tags = TagModel::SplitTags($tags);
     }
     $new_tags = array();
     $tag_ids = array();
     // See which tags are new and which ones aren't.
     foreach ($tags as $tag_id) {
         if (is_id($tag_id)) {
             $tag_ids[$tag_id] = true;
         } else {
             $new_tags[TagModel::tagSlug($tag_id)] = $tag_id;
         }
     }
     // See if any of the new tags actually exist by searching by name.
     if (!empty($new_tags)) {
         $found_tags = $this->getWhere(array('Name' => array_keys($new_tags)))->resultArray();
         foreach ($found_tags as $found_tag_row) {
             $tag_ids[$found_tag_row['TagID']] = $found_tag_row;
             unset($new_tags[TagModel::TagSlug($found_tag_row['Name'])]);
         }
     }
     // Add any remaining tags that need to be added.
     if (Gdn::session()->checkPermission('Plugins.Tagging.Add')) {
         foreach ($new_tags as $name => $full_name) {
             $new_tag = array('Name' => trim(str_replace(' ', '-', strtolower($name)), '-'), 'FullName' => $full_name, 'Type' => $new_type, 'CategoryID' => $category_id, 'InsertUserID' => Gdn::session()->UserID, 'DateInserted' => Gdn_Format::toDateTime(), 'CountDiscussions' => 0);
             $tag_id = $this->SQL->options('Ignore', true)->insert('Tag', $new_tag);
             $tag_ids[$tag_id] = true;
         }
     }
     // Grab the tags so we can see more information about them.
     $save_tags = $this->getWhere(array('TagID' => array_keys($tag_ids)))->resultArray();
     // Add any parent tags that may need to be added.
     foreach ($save_tags as $save_tag) {
         $parent_tag_id = val('ParentTagID', $save_tag);
         if ($parent_tag_id) {
             $tag_ids[$parent_tag_id] = true;
         }
         $all_tags[$save_tag['TagID']] = $save_tag;
     }
     // Remove tags that are already associated with the discussion.
     //      $same_tag_ids = array_intersect_key($tag_ids, $current_tags);
     //      $current_tags = array_diff_key($current_tags, $same_tag_ids);
     //      $tag_ids = array_diff_key($tag_ids, $same_tag_ids);
     // Figure out the tags we need to add.
     $insert_tag_ids = array_diff_key($tag_ids, $current_tags);
     // Figure out the tags we need to remove.
     $delete_tag_ids = array_diff_key($current_tags, $tag_ids);
     $now = Gdn_Format::toDateTime();
     // Insert the new tag mappings.
     foreach ($insert_tag_ids as $tag_id => $bool) {
         if (isset($all_tags[$tag_id])) {
             $insert_category_id = $all_tags[$tag_id]['CategoryID'];
         } else {
             $insert_category_id = $category_id;
         }
         $this->SQL->options('Ignore', true)->insert('TagDiscussion', array('DiscussionID' => $discussion_id, 'TagID' => $tag_id, 'DateInserted' => $now, 'CategoryID' => $insert_category_id));
     }
     // Delete the old tag mappings.
     if (!empty($delete_tag_ids)) {
         $this->SQL->delete('TagDiscussion', array('DiscussionID' => $discussion_id, 'TagID' => array_keys($delete_tag_ids)));
     }
     // Increment the tag counts.
     if (!empty($insert_tag_ids)) {
         $this->SQL->update('Tag')->set('CountDiscussions', 'CountDiscussions + 1', false)->whereIn('TagID', array_keys($insert_tag_ids))->put();
     }
     // Decrement the tag counts.
     if (!empty($delete_tag_ids)) {
         $this->SQL->update('Tag')->set('CountDiscussions', 'CountDiscussions - 1', false)->whereIn('TagID', array_keys($delete_tag_ids))->put();
     }
 }