public function createRelationship($target, $firstLabel = null, $secondLabel = null) { if ($this->isValidTarget($target)) { $relationship = new Relationships(); $relationship->firstType = get_class($this->owner); $relationship->firstId = $this->owner->id; $relationship->firstLabel = $firstLabel; $relationship->secondType = get_class($target); $relationship->secondId = $target->id; $relationship->secondLabel = $secondLabel; if ($relationship->save()) { return true; } else { return $relationship->getAllErrorMessages(); } } return false; }
public function testMergeRelationships() { $contact = $this->contact('testAnyone'); $otherContact = $this->contact('testUser'); $thirdContact = $this->contact('testUser_unsent'); $rel = new Relationships(); $rel->firstType = $rel->secondType = 'Contacts'; $rel->firstId = $contact->id; $rel->secondId = $otherContact->id; $rel->save(); $rel = new Relationships(); $rel->firstType = $rel->secondType = 'Contacts'; $rel->secondId = $contact->id; $rel->firstId = $thirdContact->id; $rel->save(); $model = new Contacts(); foreach ($contact->attributes as $key => $val) { if ($key != 'id' && $key != 'nameId') { $model->{$key} = $val; } } $model->save(); $this->assertEquals(1, count($model->getRelatedX2Models(true))); $this->assertEquals(2, count($contact->getRelatedX2Models(true))); $mergeData = $model->mergeRelationships($contact, true); $this->assertEquals(0, count($contact->getRelatedX2Models(true))); $this->assertEquals(3, count($model->getRelatedX2Models(true))); $model->unmergeRelationships($contact->id, $mergeData); $this->assertEquals(2, count($contact->getRelatedX2Models(true))); $this->assertEquals(1, count($model->getRelatedX2Models(true))); }
/** * Creates a new model. * * If creation is successful, the browser will be redirected to the 'view' page. * * @param bool $quick If true, this indicates the action is being requested via AJAX */ public function actionCreate($quick = false, $duplicate = false) { $model = new Quote(); if ($duplicate && !isset($_POST['Quote'])) { $copiedModel = Quote::model()->findByPk($duplicate); if (!empty($copiedModel)) { foreach ($copiedModel->attributes as $name => $value) { if ($name != 'id') { $model->{$name} = $value; } } $model->setLineItems($this->duplicateLineItems($copiedModel), false, true); } } $users = User::getNames(); if ($quick && !Yii::app()->request->isAjaxRequest) { throw new CHttpException(400); } $currency = Yii::app()->params->currency; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Quote'])) { $model->setX2Fields($_POST['Quote']); $model->currency = $currency; $model->createDate = time(); $model->lastUpdated = $model->createDate; $model->createdBy = Yii::app()->user->name; $model->updatedBy = $model->createdBy; if (empty($model->name)) { $model->name = ''; } if (isset($_POST['lineitem'])) { $model->lineItems = $_POST['lineitem']; } if (!$model->hasLineItemErrors) { if ($model->save()) { $model->createEventRecord(); $model->createActionRecord(); $model->saveLineItems(); if (!$quick) { $this->redirect(array('view', 'id' => $model->id)); } else { if (isset($_GET['recordId']) && isset($_GET['recordType'])) { $recordId = $_GET['recordId']; $recordType = $_GET['recordType']; $relatedModel = X2Model::model($_GET['recordType'])->findByPk($recordId); // tie record to quote if ($relatedModel) { $relate = new Relationships(); $relate->firstId = $model->id; $relate->firstType = "Quote"; $relate->secondId = $relatedModel->id; $relate->secondType = $recordType; $relate->save(); $model->createAssociatedAction(X2Model::getAssociationType(get_class($relatedModel)), $relatedModel->id); } } return; } } } } // get products $products = Product::activeProducts(); $viewData = array('model' => $model, 'users' => $users, 'products' => $products, 'quick' => $quick); if (!$quick) { $this->render('create', $viewData); } else { if ($model->hasErrors() || $model->hasLineItemErrors) { // Sneak into the response that validation failed via setting // the response code manually: header('HTTP/1.1 400 Validation Error'); } $this->renderPartial('create', $viewData, false, true); } }
public function testGetRelationships() { $contact = $this->contact('testAnyone'); $otherContact = $this->contact('testUser'); $account = $this->account('account1'); $contact1Relationships = count($contact->relationships->getRelationships()); $contact2Relationships = count($otherContact->relationships->getRelationships()); $accountRelationships = count($account->relationships->getRelationships()); $rel = new Relationships(); $rel->firstType = get_class($contact); $rel->firstId = $contact->id; $rel->secondType = get_class($otherContact); $rel->secondId = $otherContact->id; $rel->save(); $this->assertEquals($contact1Relationships + 1, count($contact->relationships->getRelationships(true))); $this->assertEquals($contact2Relationships + 1, count($otherContact->relationships->getRelationships(true))); $rel2 = new Relationships(); $rel2->firstType = get_class($contact); $rel2->firstId = $contact->id; $rel2->secondType = get_class($account); $rel2->secondId = $account->id; $rel2->save(); $this->assertEquals($contact1Relationships + 2, count($contact->relationships->getRelationships(true))); $this->assertEquals($contact2Relationships + 1, count($otherContact->relationships->getRelationships(true))); $this->assertEquals($accountRelationships + 1, count($account->relationships->getRelationships(true))); $rel->delete(); $rel2->delete(); // Verify that cache is preserved unless we manually refresh it $this->assertEquals($contact1Relationships + 2, count($contact->relationships->getRelationships())); $this->assertEquals($contact2Relationships + 1, count($otherContact->relationships->getRelationships())); $this->assertEquals($accountRelationships + 1, count($account->relationships->getRelationships())); $this->assertEquals($contact1Relationships, count($contact->relationships->getRelationships(true))); $this->assertEquals($contact2Relationships, count($otherContact->relationships->getRelationships(true))); $this->assertEquals($accountRelationships, count($account->relationships->getRelationships(true))); }
/** * Add a record to record relationship * * A record can be a contact, opportunity, or account. This function is * called via ajax from the Relationships Widget. */ public function actionAddRelationship() { //check if relationship already exits if (isset($_POST['ModelName']) && isset($_POST['ModelId']) && isset($_POST['RelationshipModelName']) && isset($_POST['RelationshipModelId'])) { $modelName = $_POST['ModelName']; $modelId = $_POST['ModelId']; $relationshipModelName = $_POST['RelationshipModelName']; $relationshipModelId = $_POST['RelationshipModelId']; $model = $this->getModelFromTypeAndId($modelName, $modelId); if (!Yii::app()->controller->checkPermissions($model, 'edit')) { $this->denied(); } $relationshipModel = $this->getModelFromTypeAndId($relationshipModelName, $relationshipModelId); if (!Yii::app()->controller->checkPermissions($relationshipModel, 'view')) { $this->denied(); } if (isset($_POST['mutual']) && $_POST['mutual'] == 'true') { $_POST['secondLabel'] = $_POST['firstLabel']; } $relationship = new Relationships(); $relationship->firstType = $_POST['ModelName']; $relationship->firstId = $_POST['ModelId']; $relationship->firstLabel = $_POST['firstLabel']; $relationship->secondType = $_POST['RelationshipModelName']; $relationship->secondId = $_POST['RelationshipModelId']; $relationship->secondLabel = $_POST['secondLabel']; if ($relationship->hasDuplicates()) { echo 'duplicate'; Yii::app()->end(); } if ($relationship->save()) { echo 'success'; Yii::app()->end(); } else { echo 'failure'; Yii::app()->end(); } } else { throw new CHttpException(400, Yii::t('app', 'Bad Request')); } }
public function actionAddContact($id) { $users = User::getNames(); unset($users['admin']); unset($users['']); foreach (Groups::model()->findAll() as $group) { $users[$group->id] = $group->name; } $contacts = Contacts::getAllNames(); unset($contacts['0']); $model = $this->loadModel($id); $contacts = Sales::editContactArray($contacts, $model); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Sales'])) { $temp = $model->associatedContacts; $tempArr = $model->attributes; $model->attributes = $_POST['Sales']; $arr = $_POST['Sales']['associatedContacts']; foreach ($arr as $contactId) { $rel = new Relationships(); $rel->firstType = 'Contacts'; $rel->firstId = $contactId; $rel->secondType = 'Sales'; $rel->secondId = $model->id; $rel->save(); } $model->associatedContacts = Sales::parseContacts($arr); $temp .= " " . $model->associatedContacts; $model->associatedContacts = $temp; $changes = $this->calculateChanges($tempArr, $model->attributes); $model = $this->updateChangelog($model, $changes); if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('addContact', array('model' => $model, 'users' => $users, 'contacts' => $contacts, 'action' => 'Add')); }
/** * REST-ful API method for adding and removing relationships between records. */ public function actionRelationship() { $rType = Yii::app()->request->requestType; switch ($rType) { case 'GET': // Look up relationships on a model $attr = array('firstType' => $_GET['model']); $relationships = Relationships::model()->findAllByAttributes(array_merge(array_intersect_key($_GET, array_flip(Relationships::model()->safeAttributeNames)), $attr)); if (empty($relationships)) { $this->_sendResponse(404, Yii::t('api', 'No relationships found.')); } else { $this->_sendResponse(200, array_map(function ($r) { return $r->attributes; }, $relationships), 1); } case 'POST': // Add a new relationship to model $relationship = new Relationships('api'); $relationship->attributes = $_POST; $relationship->firstType = $_GET['model']; if ($relationship->validate()) { $existingRelationship = Relationships::model()->findByAttributes(array_intersect_key($relationship->attributes, array_flip(array('firstType', 'secondType', 'firstId', 'secondId')))); if ($existingRelationship) { $this->_sendResponse(200, Yii::t('api', 'Such a relationship already exists.')); } if ($relationship->save()) { $this->_sendResponse(200, Yii::t('api', 'Successfully saved a relationship.')); } else { $this->_sendResponse(500, Yii::t('api', 'Failed to save relationship record for unknown reason.')); } } else { $this->response['modelErrors'] = $relationship->errors; $this->_sendResponse(400, $this->validationMsg('create', $relationship)); } break; case 'DELETE': if (!isset($_GET['secondType'], $_GET['firstId'], $_GET['secondId'])) { $this->_sendResponse(400, Yii::t('api', 'Cannot delete; no parameters specified for finding a relationship record to delete.')); } $relationships = Relationships::model()->findAllByAttributes(array_merge(array('firstType' => $_GET['model']), array_intersect_key($_GET, array_flip(Relationships::model()->attributeNames())))); if (empty($relationships)) { $this->_sendResponse(404, Yii::t('api', 'No relationships deleted; none were found matching specfied parameters.')); } $n_d = 0; $n_d_t = count($relationships); foreach ($relationships as $model) { $n_d += $model->delete() ? 1 : 0; } if ($n_d == $n_d_t) { $this->_sendResponse(200, Yii::t('api', '{n} relationships deleted.', array('{n}' => $n_d))); } else { $this->_sendResponse(500, Yii::t('api', 'One or more relationships could not be deleted.')); } break; default: $this->_sendResponse(400, Yii::t('api', 'Request type not supported for this action.')); break; } }
/** * Runs when a model is saved. * Scans attributes for phone numbers and index them in <tt>x2_phone_numbers</tt>. * Updates <tt>x2_relationships</tt> table based on link type fields. * Fires onAfterSave event. */ public function afterSave() { if ($this->_runAfterCreate) { $this->afterCreate(); } else { $this->afterUpdate(); } $phoneFields = array(); $linkFields = array(); // look through fields for phone numbers and relationships foreach (self::$_fields[$this->tableName()] as &$_field) { if ($_field->type === 'phone') { $phoneFields[$_field->fieldName] = $this->getAttribute($_field->fieldName); } elseif ($_field->type === 'link') { $nameAndId = Fields::nameAndId($this->getAttribute($_field->fieldName)); $linkFields[$_field->fieldName] = array('id' => $nameAndId[1], 'type' => $_field->linkType); } } // deal with phone numbers if (count($phoneFields)) { X2Model::model('PhoneNumber')->deleteAllByAttributes(array('modelId' => $this->id, 'modelType' => get_class($this))); } // clear out old phone numbers foreach ($phoneFields as $field => &$number) { // create new entries in x2_phone_numbers if (!empty($number)) { $num = new PhoneNumber(); $num->number = preg_replace('/\\D/', '', $number); // eliminate everything other than digits $num->modelId = $this->id; $num->modelType = get_class($this); $num->fieldName = $field; $num->save(); } } /////////////// deal with relationships /////////////// $oldAttributes = $this->getOldAttributes(); $relationSql = '(firstType=:type1 AND firstId=:id1 AND secondType=:type2 AND secondId=:id2) OR (firstType=:type2 AND firstId=:id2 AND secondType=:type1 AND secondId=:id1)'; foreach ($linkFields as $fieldName => &$relation) { list($oldLinkName, $oldLinkId) = Fields::nameAndId(isset($oldAttributes[$fieldName]) ? $oldAttributes[$fieldName] : ''); if ($relation['id'] == $oldLinkId) { // skip field if it hasn't changed continue; } // forget old relationship (wouldn't it be nice...) if (!empty($oldLinkId)) { CActiveRecord::model('Relationships')->deleteAll($relationSql, array(':type1' => get_class($this), ':id1' => $this->id, ':type2' => $relation['type'], ':id2' => $oldLinkId)); } // save new relationship if (!empty($relation['id']) && ctype_digit((string) $relation['id'])) { if (!CActiveRecord::model('Relationships')->exists($relationSql, array(':type1' => get_class($this), ':id1' => $this->id, ':type2' => $relation['type'], ':id2' => $relation['id']))) { $rel = new Relationships(); $rel->firstType = get_class($this); $rel->secondType = $relation['type']; $rel->firstId = $this->id; $rel->secondId = $relation['id']; $rel->save(); } } } parent::afterSave(); // raise onAfterSave event for behaviors, such as X2ChangeLogBehavior }
/** * Add a record to record relationship * * A record can be a contact, opportunity, or account. This function is * called via ajax from the Relationships Widget. * */ public function actionAddRelationship() { //check if relationship already exits if (isset($_POST['ModelName']) && isset($_POST['ModelId']) && isset($_POST['RelationshipModelName']) && isset($_POST['RelationshipModelId'])) { $modelName = $_POST['ModelName']; $modelId = $_POST['ModelId']; $relationshipModelName = $_POST['RelationshipModelName']; $relationshipModelId = $_POST['RelationshipModelId']; $relationship = Relationships::model()->findByAttributes(array('firstType' => $_POST['ModelName'], 'firstId' => $_POST['ModelId'], 'secondType' => $_POST['RelationshipModelName'], 'secondId' => $_POST['RelationshipModelId'])); if ($relationship) { echo "duplicate"; Yii::app()->end(); } $relationship = Relationships::model()->findByAttributes(array('firstType' => $_POST['RelationshipModelName'], 'firstId' => $_POST['RelationshipModelId'], 'secondType' => $_POST['ModelName'], 'secondId' => $_POST['ModelId'])); if ($relationship) { echo "duplicate"; Yii::app()->end(); } if (isset($_POST['mutual']) && $_POST['mutual'] == 'true') { $_POST['secondLabel'] = $_POST['firstLabel']; } $relationship = new Relationships(); $relationship->firstType = $_POST['ModelName']; $relationship->firstId = $_POST['ModelId']; $relationship->firstLabel = $_POST['firstLabel']; $relationship->secondType = $_POST['RelationshipModelName']; $relationship->secondId = $_POST['RelationshipModelId']; $relationship->secondLabel = $_POST['secondLabel']; $relationship->save(); // if($relationshipModelName == "Contacts"){ // $results = Yii::app()->db->createCommand("SELECT * from x2_relationships WHERE (firstType='Contacts' AND firstId=$relationshipModelId AND secondType='Accounts') OR (secondType='Contacts' AND secondId=$relationshipModelId AND firstType='Accounts')")->queryAll(); // if(sizeof($results) == 1){ // $model = Contacts::model()->findByPk($relationshipModelId); // if($model){ // $model->company = $modelId; // $model->update(); // } // } // } echo "success"; Yii::app()->end(); } else { throw new CHttpException(400, Yii::t('app', 'Bad Request')); } }
/** * Action for viewing or modifying relationships on a model. * * @param type $_class * @param type $_id * @param type $_relatedId */ public function actionRelationships($_class = null, $_id = null, $_relatedId = null) { $method = Yii::app()->request->requestType; $relationship = null; if ($_relatedId !== null) { $relationship = Relationships::model()->findByPk($_relatedId); if (!$relationship instanceof Relationships) { $this->send(404, "Relationship with id={$_relatedId} not found."); } // Check whether the relationship is actually attached to this model: if ($_class !== null && $_id !== null && $relationship->firstId != $this->model->id && $relationship->secondId != $this->model->id && $relationship->firstType != $_class && $relationship->secondType != $_class) { $this->response->httpHeader['Location'] = $this->createAbsoluteUrl('/api2/relationships', array('_class' => $relationship->firstType, '_id' => $relationship->firstId, '_relatedId' => $relationship->id)); $this->send(303, "Specified relationship does not correspond " . "to {$_class} record {$_id}."); } } switch ($method) { case 'GET': if ($relationship !== null) { // Get an individual relationship record. Also, include the // resource URL of the related model. $which = $relationship->firstId == $_id && $relationship->firstType == $_class ? 'second' : 'first'; $relId = $which . 'Id'; $relType = $which . 'Type'; $this->response->httpHeader['Location'] = $this->createAbsoluteUrl('/api2/model', array('_class' => $relationship->{$relType}, '_id' => $relationship->{$relId})); $this->responseBody = $relationship; } else { // Query relationships on a model. $criteria = null; if (!$relationship instanceof Relationships) { // Both ingoing and outgoing relationships. $from = new CDbCriteria(); $to = new CDbCriteria(); $from->compare('firstType', $_class); $from->compare('firstId', $_id); $to->compare('secondType', $_class); $to->compare('secondId', $_id); $criteria = new CDbCriteria(); $criteria->mergeWith($from, 'OR'); $criteria->mergeWith($to, 'OR'); } $this->responseBody = $this->getDataProvider('Relationships', $criteria)->getData(); } break; case 'PATCH': case 'POST': case 'PUT': if (!$relationship instanceof Relationships) { if ($method !== 'POST') { // Cannot PUT on a nonexistent model $this->send(405, "Method \"POST\" is required to create new relationships."); } $relationship = new Relationships(); } // Scenario kludge that adds special validation rule for the // Relations model class, which dicates that it must point to // an existing record on both ends: $relationship->setScenario('api'); $relationship->setAttributes($this->jpost); // Set missing attributes, if any: if (empty($relationship->firstType)) { $relationship->firstType = $_class; $relationship->firstId = $_id; } elseif (empty($relationship->secondType)) { $relationship->secondType = $_class; $relationship->secondId = $_id; } if (!$relationship->save()) { // Validation errors $this->response['errors'] = $relationship->errors; $this->send(422); } else { $this->responseBody = $relationship; if ($method === 'POST') { // Set location header and respond with "201 Created" $this->response->httpHeader['Location'] = $this->createAbsoluteUrl('/api2/relationships', array('_class' => $_class, '_id' => $_id, '_relatedId' => $_relatedId)); $this->send(201, "Relationship created successfully"); } } break; case 'DELETE': if (!$relationship instanceof Relationships) { $this->send(400, "Cannot delete relationships without specifying which one to delete."); } if ($relationship->delete()) { $this->sendEmpty("Relationship {$_relatedId} deleted successfully."); } else { $this->send(500, "Failed to delete relationship #{$_relatedId}. It may have been deleted already."); } break; } }
/** * Upload a file. */ public function actionUpload() { if (!isset($_FILES['upload'])) { throw new CHttpException('400', 'Invalid request.'); } if (isset($_POST['drive']) && $_POST['drive']) { // google drive $auth = new GoogleAuthenticator(); if ($auth->getAccessToken()) { $service = $auth->getDriveService(); } $createdFile = null; if (isset($service, $_SESSION['access_token'], $_FILES['upload'])) { try { $file = new Google_DriveFile(); $file->setTitle($_FILES['upload']['name']); $file->setDescription('Uploaded by X2Engine'); $file->setMimeType($_FILES['upload']['type']); if (empty($_FILES['upload']['tmp_name'])) { $err = false; switch ($_FILES['newfile']['error']) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $err .= 'File size exceeds limit of ' . get_max_upload() . ' bytes.'; break; case UPLOAD_ERR_PARTIAL: $err .= 'File upload was not completed.'; break; case UPLOAD_ERR_NO_FILE: $err .= 'Zero-length file uploaded.'; break; default: $err .= 'Internal error ' . $_FILES['newfile']['error']; break; } if ((bool) $message) { throw new CException($message); } } $data = file_get_contents($_FILES['upload']['tmp_name']); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $_FILES['upload']['type'])); if (is_array($createdFile)) { $model = new Media(); $model->fileName = $createdFile['id']; $model->name = $createdFile['title']; if (isset($_POST['associationId'])) { $model->associationId = $_POST['associationId']; } if (isset($_POST['associationType'])) { $model->associationType = $_POST['associationType']; } if (isset($_POST['private'])) { $model->private = $_POST['private']; } $model->uploadedBy = Yii::app()->user->getName(); $model->mimetype = $createdFile['mimeType']; $model->filesize = $createdFile['fileSize']; $model->drive = 1; $model->save(); if ($model->associationType == 'feed') { $event = new Events(); $event->user = Yii::app()->user->getName(); if (isset($_POST['attachmentText']) && !empty($_POST['attachmentText'])) { $event->text = $_POST['attachmentText']; } else { $event->text = Yii::t('app', 'Attached file: '); } $event->type = 'media'; $event->timestamp = time(); $event->lastUpdated = time(); $event->associationId = $model->id; $event->associationType = 'Media'; $event->save(); if (Auxlib::isAjax()) { return print "success"; } $this->redirect(array('/profile/view', 'id' => Yii::app()->user->getId())); } elseif ($model->associationType == 'docs') { if (Auxlib::isAjax()) { return print "success"; } $this->redirect(array('/docs/docs/index')); } elseif (!empty($model->associationType) && !empty($model->associationId)) { $note = new Actions(); $note->createDate = time(); $note->dueDate = time(); $note->completeDate = time(); $note->complete = 'Yes'; $note->visibility = '1'; $note->completedBy = Yii::app()->user->getName(); if ($model->private) { $note->assignedTo = Yii::app()->user->getName(); $note->visibility = '0'; } else { $note->assignedTo = 'Anyone'; } $note->type = 'attachment'; $note->associationId = $_POST['associationId']; $note->associationType = $_POST['associationType']; $association = $this->getAssociation($note->associationType, $note->associationId); if ($association != null) { $note->associationName = $association->name; } $note->actionDescription = $model->fileName . ':' . $model->id; if ($note->save()) { if (Auxlib::isAjax()) { return print "success"; } $this->redirect(array($model->associationType . '/' . $model->associationId)); } } else { if (Auxlib::isAjax()) { return print "success"; } $this->redirect('/media/media/view', array('id' => $model->id)); } } else { throw new CHttpException('400', 'Invalid request.'); } } catch (Google_AuthException $e) { $auth->flushCredentials(); $auth->setErrors($e->getMessage()); $service = null; $createdFile = null; } } else { if (isset($_SERVER['HTTP_REFERER'])) { if (Auxlib::isAjax()) { return print "success"; } $this->redirect($_SERVER['HTTP_REFERER']); } else { throw new CHttpException('400', 'Invalid request'); } } } else { // non-google drive upload $model = new Media(); $temp = CUploadedFile::getInstanceByName('upload'); // file uploaded through form if ($temp && ($tempName = $temp->getTempName()) && !empty($tempName)) { $name = $temp->getName(); $name = str_replace(' ', '_', $name); $check = Media::model()->findAllByAttributes(array('fileName' => $name)); // rename file if there name conflicts by suffixing "(n)" if (count($check) != 0) { $count = 1; $newName = $name; $arr = explode('.', $name); $name = $arr[0]; while (count($check) != 0) { $newName = $name . '(' . $count . ').' . $temp->getExtensionName(); $check = Media::model()->findAllByAttributes(array('fileName' => $newName)); $count++; } $name = $newName; } $username = Yii::app()->user->name; // copy file to user's media uploads directory if (FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$name}")) { if (isset($_POST['associationId'])) { $model->associationId = $_POST['associationId']; } if (isset($_POST['associationType'])) { $model->associationType = $_POST['associationType']; } if (isset($_POST['private'])) { $model->private = true; } $model->uploadedBy = Yii::app()->user->getName(); $model->createDate = time(); $model->lastUpdated = time(); $model->fileName = $name; $model->mimetype = $temp->type; if (!$model->save()) { $errors = $model->getErrors(); $error = ArrayUtil::pop(ArrayUtil::pop($errors)); Yii::app()->user->setFlash('top-error', Yii::t('app', 'Attachment failed. ' . $error)); if (Auxlib::isAjax()) { return print "success"; } $this->redirect(array($model->associationType . '/' . $model->associationType . '/view', 'id' => $model->associationId)); Yii::app()->end(); } else { $relatedModel = X2Model::getModelOfTypeWithId($model->associationType, $model->associationId); if ($relatedModel && $relatedModel->supportsRelationships) { $rel = new Relationships(); $rel->setFirstModel($model); $rel->setSecondModel($relatedModel); $rel->save(); } } // handle different upload types switch ($model->associationType) { case 'feed': $this->handleFeedTypeUpload($model, $name); break; case 'docs': if (Auxlib::isAjax()) { return print "success"; } $this->redirect(array('/docs/docs/index')); break; case 'loginSound': case 'notificationSound': if (Auxlib::isAjax()) { return print "success"; } $this->redirect(array('/profile/settings', 'id' => Yii::app()->user->getId())); break; case 'bg': case 'bg-private': $this->redirect(array('/profile/settings', 'bgId' => $model->id)); break; case 'none': if (Auxlib::isAjax()) { return print "success"; } break; case 'topicReply': $this->handleTopicReplyUpload($model, $name); break; default: $this->handleDefaultUpload($model, $name); break; } } } else { if (isset($_SERVER['HTTP_REFERER'])) { if (Auxlib::isAjax()) { return print "success"; } $this->redirect($_SERVER['HTTP_REFERER']); } else { throw new CHttpException('400', 'Invalid request'); } } if (isset($_GET['redirect'])) { $this->redirect($_SERVER['HTTP_REFERER']); } } }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function update($model, $oldAttributes, $api) { $name = $this->modelClass; $temp = $oldAttributes; $changes = $this->calculateChanges($temp, $model->attributes, $model); $model = $this->updateChangelog($model, $changes); if ($model->save()) { if (!$model instanceof Actions) { $fields = Fields::model()->findAllByAttributes(array('modelName' => $name, 'type' => 'link')); foreach ($fields as $field) { $fieldName = $field->fieldName; if (isset($model->{$fieldName}) && $model->{$fieldName} != "") { if (is_null(Relationships::model()->findBySql("SELECT * FROM x2_relationships WHERE \n\t\t\t\t\t\t\t\t(firstType='{$name}' AND firstId='{$model->id}' AND secondType='" . ucfirst($field->linkType) . "' AND secondId='" . $model->{$fieldName} . "') \n\t\t\t\t\t\t\t\tOR (secondType='{$name}' AND secondId='{$model->id}' AND firstType='" . ucfirst($field->linkType) . "' AND firstId='" . $model->{$fieldName} . "')"))) { $rel = new Relationships(); $rel->firstType = $name; $rel->secondType = ucfirst($field->linkType); $rel->firstId = $model->id; $rel->secondId = $model->{$fieldName}; if ($rel->save()) { if ($field->linkType != 'contacts') { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('name' => $oldAttributes[$fieldName])); } else { $pieces = explode(" ", $oldAttributes[$fieldName]); if (count($pieces) > 1) { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('firstName' => $pieces[0], 'lastName' => $pieces[1])); } } if (isset($oldRel)) { $lookup = Relationships::model()->findBySql("SELECT * FROM x2_relationships WHERE \n\t\t\t\t\t\t\t\t\t(firstType='{$name}' AND firstId='{$model->id}' AND secondType='" . ucfirst($field->linkType) . "' AND secondId='" . $oldRel->id . "') \n\t\t\t\t\t\t\t\t\tOR (secondType='{$name}' AND secondId='{$model->id}' AND firstType='" . ucfirst($field->linkType) . "' AND firstId='" . $oldRel->id . "')"); if (isset($lookup)) { $lookup->delete(); } } } } } elseif ($model->{$fieldName} == "") { if ($field->linkType != 'contacts') { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('name' => $oldAttributes[$fieldName])); } else { $pieces = explode(" ", $oldAttributes[$fieldName]); if (count($pieces) > 1) { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('firstName' => $pieces[0], 'lastName' => $pieces[1])); } } if (isset($oldRel)) { $lookup = Relationships::model()->findBySql("SELECT * FROM x2_relationships WHERE \n\t\t\t\t\t\t\t\t\t(firstType='{$name}' AND firstId='{$model->id}' AND secondType='" . ucfirst($field->linkType) . "' AND secondId='" . $oldRel->id . "') \n\t\t\t\t\t\t\t\t\tOR (secondType='{$name}' AND secondId='{$model->id}' AND firstType='" . ucfirst($field->linkType) . "' AND firstId='" . $oldRel->id . "')"); if (isset($lookup)) { $lookup->delete(); } } } } } if ($model instanceof Actions && $api == 0) { if (isset($_GET['redirect']) && $model->associationType != 'none') { // if the action has an association $this->redirect(array('/' . $model->associationType . '/default/view', 'id' => $model->associationId)); } else { // no association $this->redirect(array('/actions/default/view', 'id' => $model->id)); } // view the action } else { if ($api == 0) { $this->redirect(array('view', 'id' => $model->id)); } else { return true; } } } else { return false; } }
/** * Creates a relationship between two models. * * Before the relationship is created, this function checks that the relationship * does not already exist * @param X2Model $firstType name of the class for the first model in this relationship * @param X2Model $firstId id of the first model in this relationship * @param X2Model $secondType name of the class for the second model in this relationship * @param X2Model $secondId id of the second model in this relationship * @return true if the relationship was created, false if it already exists * */ public static function create($firstType, $firstId, $secondType, $secondId, $firstLabel = '', $secondLabel = '') { $relationship = Relationships::model()->findByAttributes(array('firstType' => $firstType, 'firstId' => $firstId, 'secondType' => $secondType, 'secondId' => $secondId)); if ($relationship) { return false; } $relationship = Relationships::model()->findByAttributes(array('firstType' => $secondType, 'firstId' => $secondId, 'secondType' => $firstType, 'secondId' => $firstId)); if ($relationship) { return false; } $relationship = new Relationships(); $relationship->firstType = $firstType; $relationship->firstId = $firstId; $relationship->firstLabel = $firstLabel; $relationship->secondType = $secondType; $relationship->secondId = $secondId; $relationship->secondLabel = $secondLabel; $relationship->save(); return true; }