Saves an existing snippet
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base
494562
public function saveSnippet($data) {
        $response=CodeBank_ClientAPI::responseBase();
        
        //Ensure logged in
        if(!Permission::check('CODE_BANK_ACCESS')) {
            $response['status']='EROR';
            $response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
            
            return $response;
        }
        
        
        try {
            $snippet=Snippet::get()->byID(intval($data->id));
            if(!empty($snippet) && $snippet!==false && $snippet->ID!=0) {
                $snippet->Title=$data->title;
                $snippet->Description=$data->description;
                $snippet->Text=$data->code;
                $snippet->Tags=$data->tags;
                
                //Ensure we're not assigning to another hidden language
                if($snippet->LanguageID!=$data->language) {
                    $lang=SnippetLanguage::get()->byID(intval($data->language));
                    if(!empty($lang) && $lang!==false && $lang->ID>0) {
                        if($lang->Hidden) {
                            $response['status']='EROR';
                            $response['message']=_t('CodeBankAPI.LANGUAGE_HIDDEN', '_You cannot assign this snippet to a hidden language');
                            
                            return $response;
                        }
                    }else {
                        throw new Exception('Language not found');
                    }
                }
                
                $snippet->LanguageID=$data->language;
                $snippet->LastEditorID=Member::currentUserID();
                $snippet->PackageID=$data->packageID;
                $snippet->write();
                
                
                $response['status']='HELO';
            }else {
                $response['status']='EROR';
                $response['message']=_t('CodeBankAPI.SNIPPET_NOT_FOUND', '_Snippet not found');
            }
        }catch(Exception $e) {
            $response['status']="EROR";
            $response['message']="Internal Server error occured";
        }
        
        
        return $response;
    }
1038401
public function save($data, $form)
    {
        $request = $this->getRequest();
        $className = $this->config()->get('tree_class');

        // Existing or new record?
        $id = $data['ID'];
        if (is_numeric($id) && $id > 0) {
            $record = DataObject::get_by_id($className, $id);
            if ($record && !$record->canEdit()) {
                return Security::permissionFailure($this);
            }
            if (!$record || !$record->ID) {
                $this->httpError(404, "Bad record ID #" . (int)$id);
            }
        } else {
            if (!singleton($this->config()->get('tree_class'))->canCreate()) {
                return Security::permissionFailure($this);
            }
            $record = $this->getNewItem($id, false);
        }

        // save form data into record
        $form->saveInto($record, true);
        $record->write();
        $this->extend('onAfterSave', $record);
        $this->setCurrentPageID($record->ID);

        $message = _t(__CLASS__ . '.SAVEDUP', 'Saved.');
        if ($this->getSchemaRequested()) {
            $schemaId = Controller::join_links($this->Link('schema/DetailEditForm'), $id);
            // Ensure that newly created records have all their data loaded back into the form.
            $form->loadDataFrom($record);
            $form->setMessage($message, 'good');
            $response = $this->getSchemaResponse($schemaId, $form);
        } else {
            $response = $this->getResponseNegotiator()->respond($request);
        }

        $response->addHeader('X-Status', rawurlencode($message));
        return $response;
    }
996463
public function createNew($data)
    {
        $result = null;
        if (is_string($data)) {
            if (strpos($data, 'http') !== 0) {
                $data = 'http://'.$data;
            }
            $parsedUrl = parse_url($data);
            switch ($parsedUrl['host']) {
                case 'www.youtube.com':
                case 'youtube.com':
                    parse_str($parsedUrl['query'], $queryFields);
                    $code = $queryFields['v'];
                    $result = new Media();
                    $video = new RemoteVideoHelper($result);
                    $video->setType('youtube');
                    $video->setCode($code);
                    $result = $video->getMedia();
                    $result->setName('Youtube '.$code);
                    break;
                case 'www.vimeo.com':
                case 'vimeo.com':
                    $code = substr($parsedUrl['path'], 1);
                    $result = new Media();
                    $video = new RemoteVideoHelper($result);
                    $video->setType('vimeo');
                    $video->setCode($code);
                    $result = $video->getMedia();
                    $result->setName('Vimeo '.$code);
                    break;
                case 'www.dailymotion.com':
                case 'dailymotion.com':
                    $code = substr($parsedUrl['path'], 7);
                    $result = new Media();
                    $video = new RemoteVideoHelper($result);
                    $video->setType('dailymotion');
                    $video->setCode($code);
                    $result = $video->getMedia();
                    $result->setName('Dailymotion '.$code);
                    break;
            }
        }

        return $result;
    }
154859
public function sendData($data)
    {
        $data = parent::sendData($data);

        return $this->response = new AopTradeCloseResponse($this, $data);
    }
605283
public function getSnippetDiff($data) {
        $response=CodeBank_ClientAPI::responseBase();
        
        
        //Get the Main Revision
        $snippet1=SnippetVersion::get()->byID(intval($data->mainRev));
        if(empty($snippet1) || $snippet1===false || $snippet1->ID==0) {
            $response['status']='EROR';
            $response['message']=_t('CodeBankAPI.MAIN_REVISION_NOT_FOUND', '_Main revision not found');
        
            return $response;
        }
        
        $snippet1=preg_replace('/\r\n|\n|\r/', "\n", $snippet1->Text);
        
        
        //Get the Comparision Revision
        $snippet2=SnippetVersion::get()->byID(intval($data->compRev));
        if(empty($snippet2) || $snippet1===false || $snippet2->ID==0) {
            $response['status']='EROR';
            $response['message']=_t('CodeBankAPI.COMPARE_REVISION_NOT_FOUND', '_Compare revision not found');
        
            return $response;
        }
        
        $snippet2=preg_replace('/\r\n|\n|\r/', "\n", $snippet2->Text);
        
        
        //Generate the diff file
        $diff=new Text_Diff('auto', array(preg_split('/\n/', $snippet2), preg_split('/\n/', $snippet1)));
        $renderer=new Text_Diff_Renderer_unified(array('leading_context_lines'=>1, 'trailing_context_lines'=>1));
        
        $response['data']=array('mainRev'=>$snippet1, 'compRev'=>$snippet2, 'diff'=>$renderer->render($diff));
        
        
        return $response;
    }
1340394
public function save($data = [])
    {
        if (!$data || count($data) == 0) {
            $data = $_POST;
        }
        $data += [
            'qsID' => null,
            'oldQsID' => null,
            'questions' => [],
        ];

        $b = $this->getBlockObject();
        $c = $b->getBlockCollectionObject();

        $db = Database::connection();
        if (intval($this->bID) > 0) {
            $q = "select count(*) as total from {$this->btTable} where bID = " . intval($this->bID);
            $total = $db->getOne($q);
        } else {
            $total = 0;
        }

        if (isset($_POST['qsID']) && $_POST['qsID']) {
            $data['qsID'] = $_POST['qsID'];
        }
        if (!$data['qsID']) {
            $data['qsID'] = time();
        }

        if (isset($data['questionSetId'])) {
            // This is specifically set when using the migration tool
            $data['qsID'] = $data['questionSetId'];
        }

        if (!$data['oldQsID']) {
            $data['oldQsID'] = $data['qsID'];
        }
        $data['bID'] = intval($this->bID);

        if (!empty($data['redirectCID'])) {
            $data['redirect'] = 1;
        } else {
            $data['redirect'] = 0;
            $data['redirectCID'] = 0;
        }

        if (empty($data['addFilesToSet'])) {
            $data['addFilesToSet'] = 0;
        }

        if (!isset($data['surveyName'])) {
            $data['surveyName'] = '';
        }

        if (!isset($data['submitText'])) {
            $data['submitText'] = '';
        }

        if (!isset($data['notifyMeOnSubmission'])) {
            $data['notifyMeOnSubmission'] = 0;
        }

        if (!isset($data['thankyouMsg'])) {
            $data['thankyouMsg'] = '';
        }

        if (!isset($data['displayCaptcha'])) {
            $data['displayCaptcha'] = 0;
        }

        $v = [$data['qsID'], $data['surveyName'], $data['submitText'], intval($data['notifyMeOnSubmission']), $data['recipientEmail'], $data['thankyouMsg'], intval($data['displayCaptcha']), intval($data['redirectCID']), intval($data['addFilesToSet']), intval($this->bID)];

        //is it new?
        if (intval($total) == 0) {
            $q = "insert into {$this->btTable} (questionSetId, surveyName, submitText, notifyMeOnSubmission, recipientEmail, thankyouMsg, displayCaptcha, redirectCID, addFilesToSet, bID) values (?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
        } else {
            $v[] = $data['qsID'];
            $q = "update {$this->btTable} set questionSetId = ?, surveyName=?, submitText=?, notifyMeOnSubmission=?, recipientEmail=?, thankyouMsg=?, displayCaptcha=?, redirectCID=?, addFilesToSet=? where bID = ? AND questionSetId= ?";
        }

        $rs = $db->query($q, $v);

        //Add Questions (for programmatically creating forms, such as during the site install)
        if (count($data['questions']) > 0) {
            $miniSurvey = new MiniSurvey();
            foreach ($data['questions'] as $questionData) {
                $miniSurvey->addEditQuestion($questionData, 0);
            }
        }

        $this->questionVersioning($data);

        return true;
    }
1068762
public function editLanguage($data) {
        $response=CodeBank_ClientAPI::responseBase();
        
        try {
            if(SnippetLanguage::get()->filter('Name:nocase', Convert::raw2sql($data->language))->Count()>0) {
                $response['status']='EROR';
                $response['message']=_t('CodeBankAPI.LANGUAGE_EXISTS', '_Language already exists');
            
                return $response;
            }
            
            
            $lang=SnippetLanguage::get()->byID(intval($data->id));
            if(empty($lang) || $lang===false || $lang->ID==0) {
                $response['status']='EROR';
                $response['message']=_t('CodeBankAPI.LANGUAGE_NOT_FOUND', '_Language not found');
                
                return $response;
            }
            
            
            //Update language and write
            if($lang->UserLanguage==true) {
                $lang->Name=$data->language;
                $lang->FileExtension=$data->fileExtension;
            }
            
            $lang->Hidden=$data->hidden;
            $lang->write();
            
            
            $response['status']='HELO';
            $response['message']="Language edited successfully";
        }catch (Exception $e) {
            $response['status']='EROR';
            $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later');
        }
        
        return $response;
    }
305212
public function save($data)
    {
        if (empty($data['_id'])) {
            return $this->insert($data);
        }

        $id = $data['_id'];

        unset($data['_id']);

        $bucketName = $this->db->quoteBucketName($this->name);

        $this->update($data, ["META($bucketName).id" => $id]);

        return $id;
    }
762475
public function append($data)
    {
        $content = file_get_contents($this->_filleFullName);
        $data = $content.PHP_EOL.$data;
        $saveToFileRes = file_put_contents($this->_filleFullName, $data);
        return $saveToFileRes;
    }
323089
public function findSnippetAutoComplete($data) {
        $response=CodeBank_ClientAPI::responseBase();
        
        //Ensure logged in
        if(!Permission::check('CODE_BANK_ACCESS')) {
            $response['status']='EROR';
            $response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
        
            return $response;
        }
        
        
        //Lookup snippets
        $snippets=Snippet::get()->filter('Title:StartsWith', Convert::raw2sql($data->pattern))->limit(20);
        
        
        $response['status']='HELO';
        $response['data']=$this->overviewList($snippets);
        
        return $response;
    }
463585
public function save($data)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$table      = $this->getTable();
		$input      = JFactory::getApplication()->input;
		$pk         = (!empty($data['id'])) ? $data['id'] : (int) $this->getState($this->getName() . '.id');
		$isNew      = true;
		$context    = $this->option . '.' . $this->name;

		// Include the plugins for the save events.
		JPluginHelper::importPlugin($this->events_map['save']);

		// Load the row if saving an existing category.
		if ($pk > 0)
		{
			$table->load($pk);
			$isNew = false;
		}

		// Set the new parent id if parent id not matched OR while New/Save as Copy .
		if ($table->parent_id != $data['parent_id'] || $data['id'] == 0)
		{
			$table->setLocation($data['parent_id'], 'last-child');
		}

		// Alter the title for save as copy
		if ($input->get('task') == 'save2copy')
		{
			$origTable = clone $this->getTable();
			$origTable->load($input->getInt('id'));

			if ($data['title'] == $origTable->title)
			{
				list($title, $alias) = $this->generateNewTitle($data['parent_id'], $data['alias'], $data['title']);
				$data['title'] = $title;
				$data['alias'] = $alias;
			}
			else
			{
				if ($data['alias'] == $origTable->alias)
				{
					$data['alias'] = '';
				}
			}

			$data['published'] = 0;
		}

		// Bind the data.
		if (!$table->bind($data))
		{
			$this->setError($table->getError());

			return false;
		}

		// Bind the rules.
		if (isset($data['rules']))
		{
			$rules = new JAccessRules($data['rules']);
			$table->setRules($rules);
		}

		// Check the data.
		if (!$table->check())
		{
			$this->setError($table->getError());

			return false;
		}

		// Trigger the before save event.
		$result = $dispatcher->trigger($this->event_before_save, array($context, &$table, $isNew));

		if (in_array(false, $result, true))
		{
			$this->setError($table->getError());

			return false;
		}

		// Store the data.
		if (!$table->store())
		{
			$this->setError($table->getError());

			return false;
		}

		$assoc = $this->getAssoc();

		if ($assoc)
		{
			// Adding self to the association
			$associations = isset($data['associations']) ? $data['associations'] : array();

			// Unset any invalid associations
			$associations = Joomla\Utilities\ArrayHelper::toInteger($associations);

			foreach ($associations as $tag => $id)
			{
				if (!$id)
				{
					unset($associations[$tag]);
				}
			}

			// Detecting all item menus
			$all_language = $table->language == '*';

			if ($all_language && !empty($associations))
			{
				JError::raiseNotice(403, JText::_('COM_CATEGORIES_ERROR_ALL_LANGUAGE_ASSOCIATED'));
			}

			// Get associationskey for edited item
			$db    = $this->getDbo();
			$query = $db->getQuery(true)
				->select($db->quoteName('key'))
				->from($db->quoteName('#__languages_associations'))
				->where($db->quoteName('context') . ' = ' . $db->quote($this->associationsContext))
				->where($db->quoteName('id') . ' = ' . (int) $table->id);
			$db->setQuery($query);
			$old_key = $db->loadResult();

			// Deleting old associations for the associated items
			$query = $db->getQuery(true)
				->delete($db->quoteName('#__languages_associations'))
				->where($db->quoteName('context') . ' = ' . $db->quote($this->associationsContext));

			if ($associations)
			{
				$query->where('(' . $db->quoteName('id') . ' IN (' . implode(',', $associations) . ') OR '
					. $db->quoteName('key') . ' = ' . $db->quote($old_key) . ')');
			}
			else
			{
				$query->where($db->quoteName('key') . ' = ' . $db->quote($old_key));
			}

			$db->setQuery($query);

			try
			{
				$db->execute();
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}

			// Adding self to the association
			if (!$all_language)
			{
				$associations[$table->language] = (int) $table->id;
			}

			if (count($associations) > 1)
			{
				// Adding new association for these items
				$key = md5(json_encode($associations));
				$query->clear()
					->insert('#__languages_associations');

				foreach ($associations as $id)
				{
					$query->values(((int) $id) . ',' . $db->quote($this->associationsContext) . ',' . $db->quote($key));
				}

				$db->setQuery($query);

				try
				{
					$db->execute();
				}
				catch (RuntimeException $e)
				{
					$this->setError($e->getMessage());

					return false;
				}
			}
		}

		// Trigger the after save event.
		$dispatcher->trigger($this->event_after_save, array($context, &$table, $isNew));

		// Rebuild the path for the category:
		if (!$table->rebuildPath($table->id))
		{
			$this->setError($table->getError());

			return false;
		}

		// Rebuild the paths of the category's children:
		if (!$table->rebuild($table->id, $table->lft, $table->level, $table->path))
		{
			$this->setError($table->getError());

			return false;
		}

		$this->setState($this->getName() . '.id', $table->id);

		// Clear the cache
		$this->cleanCache();

		return true;
	}
188568
public function save(array $data)
    {
		// All the services we need
		$main = $this->getServiceLocator()->get('neobazaar.service.main');
		$em = $main->getEntityManager();
		$documentRepository = $main->getDocumentEntityRepository();
		$userRepository = $main->getUserEntityRepository();
		$locationRepository = $main->getGeonamesEntityRepository();
		$cache = $this->getServiceLocator()->get('ClassifiedCache');
		$auth = $this->getServiceLocator()->get('ControllerPluginManager')->get('zfcUserAuthentication');
		$form = $this->getServiceLocator()->get('document.form.classifiedadd');
		
		$user = isset($data['user']) && is_array($data['user']) ? $data['user'] : null;
		$userId = null !== $user && isset($user['id']) ? $user['id'] : null;
		$email = isset($user['email']) ? $user['email'] : null;
		$name = isset($user['name']) ? $user['name'] : null;
		
		$document = isset($data['document']) && is_array($data['document']) ? $data['document'] : null;
		$documentId = null !== $document && isset($document['id']) ? $document['id'] : null;

		$children = isset($document["children"]) && is_array($document['children']) ? 
			$document["children"] : array();
		$metadata = isset($document['metadata']) && is_array($document['metadata']) ? 
			$document['metadata'] : array();
		
		$location = null;
		$locationUrl = isset($document["location"]) ? $document["location"] : null;
		
		if(null === $document) {
			throw new \Exception('Trying to save an empty document');
		}
		
		$data["document"]["documentType"] = Document::DOCUMENT_TYPE_CLASSIFIED;
		
		foreach($children as $k => $child) {
			if(!isset($child["content"])) {
				continue;
			}
			$image = $documentRepository->findByEncryptedId(
				$child["content"],
				'documentId'
			);
			unset($data["document"]["children"][$k]["content"]);
			$data["document"]["children"][$k]["documentId"] = $image->getDocumentId();
			$data["document"]["children"][$k]["documentType"] = Document::DOCUMENT_TYPE_IMAGE;
		}
		
		if(null !== $userId) {
			$repo = $main->getUserEntityRepository();
			$user = $repo->findByEncryptedId($userId, 'userId');
		} elseif(null !== $email) {
			$user = $userRepository->findOneBy(array('email' => $email));
			if(null === $user) {
				// @todo: validate email before insert
				$userService = $this->getServiceLocator()->get('user.service.user');
				
				// This was previously called $data and nothing worked, wonder why??
				$userdata = array();
				// This ws will take only CREATION of user, state will be always DEACTIVE
				$userdata['state'] = UserEntity::USER_STATE_DEACTIVE;
				// Edit these in the future for nicer localization and authorization
				$userdata['locale'] = 'it_IT';
				$userdata['role'] = 'guest';
				$userdata['email'] = $email;
				$userdata['name'] = $name;
				
				// This is necessary for validation
				$userdata['agreeterms'] = 1;
				$userdata['surname'] = $name;
					
				try {
					$user = $userService->save($userdata, false); // second arg for NOT to trigger event
				} catch(\Exception $e) {}
			}
		}
		
		$theUserId = $user instanceof UserEntity ? $user->getUserId() : null;
		$data["document"] = array_merge($data["document"], array('user' => $theUserId));
		
		$data["user"] = array(
			'name' => $name,
			'email' => $email
		);
		
		foreach($metadata as $meta) {
			if(isset($meta['key']) && 'comune' == $meta['key']) {
				$location = isset($meta['value']) && !empty($meta['value']) ? $meta['value'] : null;
				$location = $locationRepository->findOneBy(array('url' => $location));
				$data["document"]["geoname"] = $location ? $location->getGeonameId() : '';
				break;
			}
		}
		
		if (isset($document["location"]) && null === $location && null !== $locationUrl) {
			$location = $locationRepository->findOneBy(array('url' => $locationUrl));
			$data["document"]["geoname"] = $location instanceof GeonamesEntity
				? $location->getGeonameId() : '';
		}
		
		// @todo: get from a service
		if(null === $documentId) {
			$entity = new Document();
		} else {
			$repo = $main->getDocumentEntityRepository();
			$entity = $repo->findByEncryptedId($documentId, 'documentId');
		}
    	
		if(null === $documentId) {
			$data["document"]["state"] = $auth->hasIdentity() ? 
				Document::DOCUMENT_STATE_ACTIVE : Document::DOCUMENT_STATE_DEACTIVE;
		} else {
			$data["document"]["state"] = $entity->getState();
		}
		
		// checking for permission, only if we are in edit mode
		if(!$this->checkIfOwnerOrAdmin($entity) && null !== $documentId) {
			throw new \Exception('Non possiedi i permessi per agire su questo documento');
		}
		
		$form->setData($data);
		$form->bind($entity);
		
		if (!$form->isValid()) {
			throw new \Exception(serialize($form->getMessages()));
		}
		
		$em->persist($entity);
		$em->flush();
		$key = $documentRepository->getEncryptedId($entity->getDocumentId());
		if($cache->hasItem($key)) {
			$cache->removeItem($key);
		}
		
		// Depending on existence of $documentId will be dispatched the correct event
		if($documentId) {
		    
		} else {
		    $url = $this->getServiceLocator()->get('ControllerPluginManager')->get('Url');
		    $classifiedModel = $this->getServiceLocator()->get('document.model.classifiedAdminListing');
		    $classifiedModel->init($entity, $this->getServiceLocator());
		    $event = new ClassifiedCreatedEvent(__FUNCTION__, null, array(
    		    'to' => $classifiedModel->email, 
    		    'siteurl' => $url->fromRoute('home', array(), array('force_canonical' => true)),
    		    'fullname' => $classifiedModel->fullname,
		        'title' => $classifiedModel->title, 
		        'hash' => $classifiedModel->hashId,
		        'state' => $classifiedModel->state
    		));
		    $this->getEventManager()->trigger('classifiedCreated.post', $this, $event);
		}
		
		return $entity;
    }
1258581
public function save($data = null)
    {

        //1. Check if we have data and deal with it!
        if (!is_null($data)) {
            if (!$this->bindData($data)) {
                //we could not save the data
                return false;
            }
        }
        //2. Check if the primary key has a value
        $primary = $this->keys();

        //3. if the primary key has a value, then we are updating, else we are inserting
        if (isset($primary->Value) && !empty($primary->Value)) {
            return $this->update($primary->Value);
        } else {
            return $this->insert();
        }
        //if we get here then there is a problem
        return false;
    }
961169
public function save($data)
	{
		$related = $this->related;
		$model   = $related::newFromResults($data);

		return $this->associate($model)->save();
	}
590249
protected function save( $data ){
		if( !$this->cacheFile )
			return;
		$last	= array(
			'ip'		=> $this->lastIp,
			'timestamp'	=> $this->lastCheck
		);
		$data	= array_merge( $last,  $data );
		return FS_File_Writer::save( $this->cacheFile, json_encode( $data ) );
	}
612171
public function createLanguage($data) {
        $response=CodeBank_ClientAPI::responseBase();
        
        try {
            if(SnippetLanguage::get()->filter('Name:nocase', Convert::raw2sql($data->language))->Count()>0) {
                $response['status']='EROR';
                $response['message']=_t('CodeBankAPI.LANGUAGE_EXISTS', '_Language already exists');
                
                return $response;
            }
            
            
            $lang=new SnippetLanguage();
            $lang->Name=$data->language;
            $lang->FileExtension=$data->fileExtension;
            $lang->HighlightCode='Plain';
            $lang->UserLanguage=1;
            $lang->write();
            
            
            $response['status']='HELO';
            $response['message']="Language added successfully";
        }catch (Exception $e) {
            $response['status']='EROR';
            $response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later');
        }
        
        return $response;
    }
624988
public function save($data = null)
    {
        if ($data !== null) {
            $this->data = $data;
        }

        return $this->getHandler()->renderPath($this->getPath(), $this->data);
    }