/** * @author Ignacio Vazquez - elpepe.uy at gmail.com * @param unknown_type $object * @param unknown_type $ignored */ function core_dimensions_after_update($object, &$ignored) { static $objectsProcessed = array(); if ($object instanceof Contact && !array_var($objectsProcessed, $object->getId())) { $person_dim = Dimensions::findOne(array("conditions" => "`code` = 'feng_persons'")); $person_ot = ObjectTypes::findOne(array("conditions" => "`name` = 'person'")); $company_ot = ObjectTypes::findOne(array("conditions" => "`name` = 'company'")); $members = Members::findByObjectId($object->getId(), $person_dim->getId()); if (count($members) == 1) { /* @var $member Member */ $member = $members[0]; $member->setName($object->getObjectName()); $parent_member_id = $member->getParentMemberId(); $depth = $member->getDepth(); if ($object->getCompanyId() > 0) { $pmember = Members::findOne(array('conditions' => '`object_id` = ' . $object->getCompanyId() . ' AND `object_type_id` = ' . $company_ot->getId() . ' AND `dimension_id` = ' . $person_dim->getId())); $member->setParentMemberId($pmember->getId()); $member->setDepth($pmember->getDepth() + 1); } else { //Is first level $member->setDepth(1); $member->setParentMemberId(0); } $object->modifyMemberValidations($member); $member->save(); // reload only if not disabling or enabling user if (!(array_var($_REQUEST, 'c') == 'account' && (array_var($_REQUEST, 'a') == 'disable' || array_var($_REQUEST, 'a') == 'restore_user'))) { evt_add("reload dimension tree", $member->getDimensionId()); } $objectsProcessed[$object->getId()] = true; } } }
/** * Helper to create planning for an order * * @param unknown_type $order */ public function createPlanning($order) { //delete planning if exists (as we create it :)) $planning = mage::getModel('Purchase/SalesOrderPlanning')->load($order->getId(), 'psop_order_id'); if ($planning->getId()) { $planning->delete(); } //create & init information $planning = mage::getModel('Purchase/SalesOrderPlanning'); $planning->setpsop_order_id($order->getId()); $planning->setConsiderationInformation($order); $planning->setFullStockInformation($order); $planning->setShippingInformation($order); $planning->setDeliveryInformation($order); return $planning; }
/** * Отписка от блога или пользователя * */ protected function EventUnsubscribe() { $this->Viewer_SetResponseAjax('json'); if (!getRequest('id')) { $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error')); return; } $sType = getRequest('type'); $iType = null; /** * Определяем от чего отписываемся */ switch ($sType) { case 'blogs': $iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG; break; case 'users': $iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER; break; default: $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error')); return; } /** * Отписываем пользователя */ $this->Userfeed_unsubscribeUser($this->oUserCurrent->getId(), $iType, getRequest('id')); $this->Message_AddNotice($this->Lang_Get('userfeed_subscribes_updated'), $this->Lang_Get('attention')); }
/** * Creates customer points transfers * * @param unknown_type $customer * @param unknown_type $like_id * @param unknown_type $rule * @return unknown */ public function createFacebookLikePoints($customer, $like_id, $rule) { $num_points = $rule->getPointsAmount(); $currency_id = $rule->getPointsCurrencyId(); $rule_id = $rule->getId(); $transfer = $this->initTransfer($num_points, $currency_id, $rule_id); $store = $customer->getStore(); if (!$transfer) { return false; } //get On-Hold initial status override if ($rule->getOnholdDuration() > 0) { $transfer->setEffectiveStart(date('Y-m-d H:i:s', strtotime("+{$rule->getOnholdDuration()} days")))->setStatus(null, TBT_Rewards_Model_Transfer_Status::STATUS_PENDING_TIME); } else { //get the default starting status $initial_status = Mage::getStoreConfig('rewards/InitialTransferStatus/AfterFacebookLike', $store); if (!$transfer->setStatus(null, $initial_status)) { return false; } } // Translate the message through the core translation engine (nto the store view system) in case people want to use that instead // This is not normal, but we found that a lot of people preferred to use the standard translation system insteaed of the // store view system so this lets them use both. $initial_transfer_msg = Mage::getStoreConfig('rewards/transferComments/facebookLike', $store); $comments = Mage::helper('rewards')->__($initial_transfer_msg); $this->setFacebookLikeId($like_id)->setComments($comments)->setCustomerId($customer->getId())->save(); return true; }
/** * Helper function for rendering a resource inside this container * * @param unknown_type $resource * @access protected */ protected function render($resource) { $html = "<{$this->htmlElement}"; foreach ($this->attributes as $k => $v) { $html .= " {$k}=\"{$v}\""; } $html .= " puny=\"{$resource->getId()}\">" . "{$resource->parse()->getContent()}" . "</{$this->htmlElement}>"; return $html; }
/** * Add rule to filter * * * @param unknown_type $rule */ public function addRuleToFilter($rule) { if ($rule instanceof Mage_SalesRule_Model_Rule) { $ruleId = $rule->getId(); } else { $ruleId = (int) $rule; } $this->addFieldToFilter('rule_id', $ruleId); }
/** * Отписка от пользователя * */ protected function EventUnsubscribe() { $this->Viewer_SetResponseAjax('json'); if (!$this->User_getUserById(getRequest('id'))) { $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error')); } /** * Отписываем */ $this->Stream_unsubscribeUser($this->oUserCurrent->getId(), getRequest('id')); $this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention')); }
/** * Отправляем уведомление всем кому имеет смысл знать * 1. Подписчикам сообщества, если включили опцию и хватает прав доступа. * 2. Друзьям(подписчикам автора), если они включили данную опцию и хватает прав доступа. * 3. Владельцу блога * * @param unknown_type $oBlog * @param unknown_type $oTopic * @param unknown_type $oUserTopic */ public function SendNotifyTopicNew($oBlog, $oTopic, $oUserTopic) { $aExceptUserId = array($oTopic->getUserId(), $oBlog->getOwnerId()); $aBlogSubscriberId = $this->Notify_SendNotificationsToBlogSubscribers($oTopic, $oBlog, $aExceptUserId); if (is_array($aBlogSubscriberId)) { $aExceptUserId = array_merge($aExceptUserId, $aBlogSubscriberId); } $this->Notify_SendNotificationsToAuthorFriends($oTopic, $oBlog, $aExceptUserId); //отправляем создателю блога if ($oBlog->getOwnerId() != $oUserTopic->getId()) { $this->Notify_SendTopicNewToSubscribeBlog($oBlog->getOwner(), $oTopic, $oBlog, $oUserTopic); } }
/** * Выполняется при завершении работы экшена * */ public function EventShutdown() { if (!$this->oUserProfile) { return; } /** * Загружаем в шаблон необходимые переменные */ $iCountTopicUser = $this->Topic_GetCountTopicsPersonalByUser($this->oUserProfile->getId(), 1); $iCountCommentUser = $this->Comment_GetCountCommentsByUserId($this->oUserProfile->getId(), 'topic'); $this->Viewer_Assign('oUserProfile', $this->oUserProfile); $this->Viewer_Assign('iCountTopicUser', $iCountTopicUser); $this->Viewer_Assign('iCountCommentUser', $iCountCommentUser); }
public function EventShutdown() { if (!$this->oUserCurrent) { return; } $iCountTalkFavourite = $this->Talk_GetCountTalksFavouriteByUserId($this->oUserCurrent->getId()); $this->Viewer_Assign('iCountTalkFavourite', $iCountTalkFavourite); /** * Передаем во вьевер константы состояний участников разговора */ $this->Viewer_Assign('TALK_USER_ACTIVE', ModuleTalk::TALK_USER_ACTIVE); $this->Viewer_Assign('TALK_USER_DELETE_BY_SELF', ModuleTalk::TALK_USER_DELETE_BY_SELF); $this->Viewer_Assign('TALK_USER_DELETE_BY_AUTHOR', ModuleTalk::TALK_USER_DELETE_BY_AUTHOR); }
/** * Load primary coupon (is_primary = 1) for specified rule * * * @param Mage_SalesRule_Model_Coupon $object * @param unknown_type $rule * @return unknown */ public function loadPrimaryByRule(Mage_SalesRule_Model_Coupon $object, $rule) { $read = $this->_getReadAdapter(); if ($rule instanceof Mage_SalesRule_Model_Rule) { $ruleId = $rule->getId(); } else { $ruleId = (int) $rule; } $select = $read->select()->from($this->getMainTable())->where('rule_id = :rule_id')->where('is_primary = :is_primary'); $data = $read->fetchRow($select, array(':rule_id' => $ruleId, ':is_primary' => 1)); if (!$data) { return false; } $object->setData($data); $this->_afterLoad($object); return true; }
/** * Выполняется при завершении работы экшена */ public function EventShutdown() { if (!$this->oUserProfile) { return; } /** * Загружаем в шаблон необходимые переменные */ $iCountTopicFavourite = $this->Topic_GetCountTopicsFavouriteByUserId($this->oUserProfile->getId()); $iCountTopicUser = $this->Topic_GetCountTopicsPersonalByUser($this->oUserProfile->getId(), 1); $iCountCommentUser = $this->Comment_GetCountCommentsByUserId($this->oUserProfile->getId(), 'topic'); $iCountCommentFavourite = $this->Comment_GetCountCommentsFavouriteByUserId($this->oUserProfile->getId()); $this->Viewer_Assign('oUserProfile', $this->oUserProfile); $this->Viewer_Assign('iCountTopicUser', $iCountTopicUser); $this->Viewer_Assign('iCountCommentUser', $iCountCommentUser); $this->Viewer_Assign('iCountTopicFavourite', $iCountTopicFavourite); $this->Viewer_Assign('iCountCommentFavourite', $iCountCommentFavourite); $this->Viewer_Assign('USER_FRIEND_NULL', ModuleUser::USER_FRIEND_NULL); $this->Viewer_Assign('USER_FRIEND_OFFER', ModuleUser::USER_FRIEND_OFFER); $this->Viewer_Assign('USER_FRIEND_ACCEPT', ModuleUser::USER_FRIEND_ACCEPT); $this->Viewer_Assign('USER_FRIEND_REJECT', ModuleUser::USER_FRIEND_REJECT); $this->Viewer_Assign('USER_FRIEND_DELETE', ModuleUser::USER_FRIEND_DELETE); }
/** * Генерирует новый инвайт * * @param unknown_type $oUser * @return unknown */ public function GenerateInvite($oUser) { $oInvite = Engine::GetEntity('User_Invite'); $oInvite->setCode(func_generator(32)); $oInvite->setDateAdd(date("Y-m-d H:i:s")); $oInvite->setUserFromId($oUser->getId()); return $this->AddInvite($oInvite); }
/** * Рекурсивно обновляет полный URL у всех дочерних страниц(веток) * * @param unknown_type $oPageStart */ public function RebuildUrlFull($oPageStart) { $aPages = $this->GetPagesByPid($oPageStart->getId()); foreach ($aPages as $oPage) { if ($oPage->getId() == $oPageStart->getId()) { continue; } if (in_array($oPage->getId(), $this->aRebuildIds)) { continue; } $this->aRebuildIds[] = $oPage->getId(); $oPage->setUrlFull($oPageStart->getUrlFull() . '/' . $oPage->getUrl()); $this->UpdatePage($oPage); $this->RebuildUrlFull($oPage); } }
/** * Enter description here ... * * @param unknown_type $collection * @param unknown_type $attribute * @param unknown_type $value * @return Mage_CatalogIndex_Model_Resource_Attribute */ public function applyFilterToCollection($collection, $attribute, $value) { /** * Will be used after SQL review */ // if ($collection->isEnabledFlat()) { // $collection->getSelect()->where("e.{$attribute->getAttributeCode()}=?", $value); // return $this; // } $alias = 'attr_index_' . $attribute->getId(); $collection->getSelect()->join(array($alias => $this->getMainTable()), $alias . '.entity_id=e.entity_id', array())->where($alias . '.store_id = ?', $this->getStoreId())->where($alias . '.attribute_id = ?', $attribute->getId())->where($alias . '.value = ?', $value); return $this; }
/** * Обработка редактирования топика * * @param unknown_type $oTopic * @return unknown */ protected function SubmitEdit($oTopic) { /** * Проверка корректности полей формы */ if (!$this->checkTopicFields($oTopic)) { return false; } /** * Определяем в какой блог делаем запись */ $iBlogId = getRequest('blog_id'); if ($iBlogId == 0) { $oBlog = $this->Blog_GetPersonalBlogByUserId($oTopic->getUserId()); } else { $oBlog = $this->Blog_GetBlogById($iBlogId); } /** * Если блог не определен выдаем предупреждение */ if (!$oBlog) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'), $this->Lang_Get('error')); return false; } /** * Проверяем права на постинг в блог */ if (!$this->ACL_IsAllowBlog($oBlog, $this->oUserCurrent)) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'), $this->Lang_Get('error')); return false; } /** * Проверяем разрешено ли постить топик по времени */ if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) { $this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'), $this->Lang_Get('error')); return; } /** * Сохраняем старое значение идентификатора блога */ $sBlogIdOld = $oTopic->getBlogId(); /** * Теперь можно смело редактировать топик */ $oTopic->setBlogId($oBlog->getId()); $oTopic->setText(htmlspecialchars(getRequest('topic_text'))); $oTopic->setTextShort(htmlspecialchars(getRequest('topic_text'))); $oTopic->setTextSource(getRequest('topic_text')); $oTopic->setTags(getRequest('topic_tags')); $oTopic->setUserIp(func_getIp()); /** * изменяем вопрос/ответы только если еще никто не голосовал */ if ($oTopic->getQuestionCountVote() == 0) { $oTopic->setTitle(getRequest('topic_title')); $oTopic->clearQuestionAnswer(); foreach (getRequest('answer', array()) as $sAnswer) { $oTopic->addQuestionAnswer($sAnswer); } } $oTopic->setTextHash(md5($oTopic->getType() . $oTopic->getText() . $oTopic->getTitle())); /** * Проверяем топик на уникальность */ if ($oTopicEquivalent = $this->Topic_GetTopicUnique($this->oUserCurrent->getId(), $oTopic->getTextHash())) { if ($oTopicEquivalent->getId() != $oTopic->getId()) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_text_error_unique'), $this->Lang_Get('error')); return false; } } /** * Публикуем или сохраняем в черновиках */ $bSendNotify = false; if (isset($_REQUEST['submit_topic_publish'])) { $oTopic->setPublish(1); if ($oTopic->getPublishDraft() == 0) { $oTopic->setPublishDraft(1); $oTopic->setDateAdd(date("Y-m-d H:i:s")); $bSendNotify = true; } } else { $oTopic->setPublish(0); } /** * Принудительный вывод на главную */ if ($this->ACL_IsAllowPublishIndex($this->oUserCurrent)) { if (getRequest('topic_publish_index')) { $oTopic->setPublishIndex(1); } else { $oTopic->setPublishIndex(0); } } /** * Запрет на комментарии к топику */ $oTopic->setForbidComment(0); if (getRequest('topic_forbid_comment')) { $oTopic->setForbidComment(1); } $this->Hook_Run('topic_edit_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog)); /** * Сохраняем топик */ if ($this->Topic_UpdateTopic($oTopic)) { $this->Hook_Run('topic_edit_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog, 'bSendNotify' => &$bSendNotify)); /** * Обновляем данные в комментариях, если топик был перенесен в новый блог */ if ($sBlogIdOld != $oTopic->getBlogId()) { $this->Comment_UpdateTargetParentByTargetId($oTopic->getBlogId(), 'topic', $oTopic->getId()); $this->Comment_UpdateTargetParentByTargetIdOnline($oTopic->getBlogId(), 'topic', $oTopic->getId()); } /** * Обновляем количество топиков в блоге */ if ($sBlogIdOld != $oTopic->getBlogId()) { $this->Blog_RecalculateCountTopicByBlogId($sBlogIdOld); } $this->Blog_RecalculateCountTopicByBlogId($oTopic->getBlogId()); /** * Добавляем событие в ленту */ $this->Stream_write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && $oBlog->getType() != 'close'); /** * Рассылаем о новом топике подписчикам блога */ if ($bSendNotify) { $this->Topic_SendNotifyTopicNew($oBlog, $oTopic, $this->oUserCurrent); } if (!$oTopic->getPublish() and !$this->oUserCurrent->isAdministrator() and $this->oUserCurrent->getId() != $oTopic->getUserId()) { Router::Location($oBlog->getUrlFull()); } Router::Location($oTopic->getUrl()); } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error')); return Router::Action('error'); } }
/** * @deprecated by listing(args) * @param unknown_type $context * @param unknown_type $object_type * @param unknown_type $order * @param unknown_type $order_dir * @param unknown_type $extra_conditions * @param unknown_type $join_params * @param unknown_type $trashed * @param unknown_type $archived * @param unknown_type $start * @param unknown_type $limit */ static function getContentObjects($context, $object_type, $order = null, $order_dir = null, $extra_conditions = null, $join_params = null, $trashed = false, $archived = false, $start = 0, $limit = null) { $table_name = $object_type->getTableName(); $object_type_id = $object_type->getId(); //Join conditions $join_conditions = self::prepareJoinConditions($join_params); //Trash && Archived conditions $conditions = self::prepareTrashandArchivedConditions($trashed, $archived); $trashed_cond = $conditions[0]; $archived_cond = $conditions[1]; //Order conditions $order_conditions = self::prepareOrderConditions($order, $order_dir); //Extra conditions if (!$extra_conditions) { $extra_conditions = ""; } //Dimension conditions $member_conditions = self::prepareDimensionConditions($context, $object_type_id); if ($member_conditions == "") { $member_conditions = "true"; } $limit_query = ""; if ($limit !== null) { $limit_query = "LIMIT {$start} , {$limit} "; } $sql_count = "SELECT COUNT( DISTINCT `om`.`object_id` ) AS total FROM `" . TABLE_PREFIX . "object_members` `om` \r\n \t\tINNER JOIN `" . TABLE_PREFIX . "objects` `o` ON `o`.`id` = `om`.`object_id`\r\n \t\tINNER JOIN `" . TABLE_PREFIX . "{$table_name}` `e` ON `e`.`object_id` = `o`.`id`\r\n \t\t{$join_conditions} WHERE {$trashed_cond} {$archived_cond} AND ({$member_conditions}) {$extra_conditions}"; $total = array_var(DB::executeOne($sql_count), "total"); $sql = "SELECT DISTINCT `om`.`object_id` FROM `" . TABLE_PREFIX . "object_members` `om` \r\n \t\tINNER JOIN `" . TABLE_PREFIX . "objects` `o` ON `o`.`id` = `om`.`object_id`\r\n \t\tINNER JOIN `" . TABLE_PREFIX . "{$table_name}` `e` ON `e`.`object_id` = `o`.`id`\r\n \t\t{$join_conditions} WHERE {$trashed_cond} {$archived_cond} AND ({$member_conditions}) {$extra_conditions} {$order_conditions}\r\n \t\t{$limit_query}\r\n \t\t"; $result = DB::execute($sql); $rows = $result->fetchAll(); $objects = array(); $handler_class = $object_type->getHandlerClass(); if (!is_null($rows)) { $ids = array(); foreach ($rows as $row) { $ids[] = array_var($row, 'object_id'); } if (count($ids) > 0) { $join_str = ""; if ($join_params) { $join_str = ', "join" => array('; if (isset($join_params['join_type'])) { $join_str .= '"join_type" => "' . $join_params['join_type'] . '",'; } if (isset($join_params['table'])) { $join_str .= '"table" => "' . $join_params['table'] . '",'; } if (isset($join_params['jt_field'])) { $join_str .= '"jt_field" => "' . $join_params['jt_field'] . '",'; } if (isset($join_params['e_field'])) { $join_str .= '"e_field" => "' . $join_params['e_field'] . '",'; } if (isset($join_params['j_sub_q'])) { $join_str .= '"j_sub_q" => "' . $join_params['j_sub_q'] . '",'; } if (str_ends_with($join_str, ",")) { $join_str = substr($join_str, 0, strlen($join_str) - 1); } $join_str .= ')'; } $phpCode = '$objects = ' . $handler_class . '::findAll(array("conditions" => "`e`.`object_id` IN (' . implode(',', $ids) . ')", "order" => "' . str_replace("ORDER BY ", "", $order_conditions) . '"' . $join_str . '));'; eval($phpCode); } } $result = new stdClass(); $result->objects = $objects; $result->total = $total; return $result; }
/** * Private * * @param unknown_type $section */ function _addToHash(&$section) { //add new section to flat array $this->aSectionsMap[$section->getId()] =& $section; }
/** * Выводит форму для редактирования профиля и обрабатывает её * */ protected function EventProfile() { $this->Viewer_AddHtmlTitle($this->Lang_Get('settings_menu_profile')); /** * Если нажали кнопку "Сохранить" */ if (isPost('submit_profile_edit')) { $this->Security_ValidateSendForm(); $bError = false; /** * Заполняем профиль из полей формы */ /** * Проверяем имя */ if (func_check(getRequest('profile_name'), 'text', 2, 20)) { $this->oUserCurrent->setProfileName(getRequest('profile_name')); } else { $this->oUserCurrent->setProfileName(null); } /** * Проверка мыла */ if (func_check(getRequest('mail'), 'mail')) { if ($oUserMail = $this->User_GetUserByMail(getRequest('mail')) and $oUserMail->getId() != $this->oUserCurrent->getId()) { $this->Message_AddError($this->Lang_Get('settings_profile_mail_error_used'), $this->Lang_Get('error')); $bError = true; } else { $this->oUserCurrent->setMail(getRequest('mail')); } } else { $this->Message_AddError($this->Lang_Get('settings_profile_mail_error'), $this->Lang_Get('error')); $bError = true; } /** * Проверяем пол */ if (in_array(getRequest('profile_sex'), array('man', 'woman', 'other'))) { $this->oUserCurrent->setProfileSex(getRequest('profile_sex')); } else { $this->oUserCurrent->setProfileSex('other'); } /** * Проверяем дату рождения */ if (func_check(getRequest('profile_birthday_day'), 'id', 1, 2) and func_check(getRequest('profile_birthday_month'), 'id', 1, 2) and func_check(getRequest('profile_birthday_year'), 'id', 4, 4)) { $this->oUserCurrent->setProfileBirthday(date("Y-m-d H:i:s", mktime(0, 0, 0, getRequest('profile_birthday_month'), getRequest('profile_birthday_day'), getRequest('profile_birthday_year')))); } else { $this->oUserCurrent->setProfileBirthday(null); } /** * Проверяем страну */ if (func_check(getRequest('profile_country'), 'text', 1, 30)) { $this->oUserCurrent->setProfileCountry(getRequest('profile_country')); } else { $this->oUserCurrent->setProfileCountry(null); } /** * Проверяем регион * пока отключим регион, т.к. не понятно нужен ли он вообще =) */ /* if (func_check(getRequest('profile_region'),'text',1,30)) { $this->oUserCurrent->setProfileRegion(getRequest('profile_region')); } else { $this->oUserCurrent->setProfileRegion(null); } */ /** * Проверяем город */ if (func_check(getRequest('profile_city'), 'text', 1, 30)) { $this->oUserCurrent->setProfileCity(getRequest('profile_city')); } else { $this->oUserCurrent->setProfileCity(null); } /** * Проверяем ICQ */ if (func_check(getRequest('profile_icq'), 'id', 4, 15)) { $this->oUserCurrent->setProfileIcq(getRequest('profile_icq')); } else { $this->oUserCurrent->setProfileIcq(null); } /** * Проверяем сайт */ if (func_check(getRequest('profile_site'), 'text', 3, 200)) { $this->oUserCurrent->setProfileSite(getRequest('profile_site')); } else { $this->oUserCurrent->setProfileSite(null); } /** * Проверяем название сайта */ if (func_check(getRequest('profile_site_name'), 'text', 3, 50)) { $this->oUserCurrent->setProfileSiteName(getRequest('profile_site_name')); } else { $this->oUserCurrent->setProfileSiteName(null); } /** * Проверяем информацию о себе */ if (func_check(getRequest('profile_about'), 'text', 1, 3000)) { $this->oUserCurrent->setProfileAbout(getRequest('profile_about')); } else { $this->oUserCurrent->setProfileAbout(null); } /** * Проверка на смену пароля */ if (getRequest('password', '') != '') { if (func_check(getRequest('password'), 'password', 5)) { if (getRequest('password') == getRequest('password_confirm')) { if (func_encrypt(getRequest('password_now')) == $this->oUserCurrent->getPassword()) { $this->oUserCurrent->setPassword(func_encrypt(getRequest('password'))); } else { $bError = true; $this->Message_AddError($this->Lang_Get('settings_profile_password_current_error'), $this->Lang_Get('error')); } } else { $bError = true; $this->Message_AddError($this->Lang_Get('settings_profile_password_confirm_error'), $this->Lang_Get('error')); } } else { $bError = true; $this->Message_AddError($this->Lang_Get('settings_profile_password_new_error'), $this->Lang_Get('error')); } } /** * Загрузка аватара, делаем ресайзы */ if (isset($_FILES['avatar']) and is_uploaded_file($_FILES['avatar']['tmp_name'])) { /** * Получаем список текущих аватаров */ $sPathOld = $this->oUserCurrent->getProfileAvatar(); $aUserAvatars = array(); if ($sPathOld) { foreach (array_merge(Config::Get('module.user.avatar_size'), array(100)) as $iSize) { $aUserAvatars[$iSize] = $this->oUserCurrent->getProfileAvatarPath($iSize); } } if ($sPath = $this->User_UploadAvatar($_FILES['avatar'], $this->oUserCurrent)) { $this->oUserCurrent->setProfileAvatar($sPath); /** * Удаляем старые, если путь не совпадает с текущими аватарками */ if ($sPathOld and $sPath != $sPathOld and count($aUserAvatars)) { foreach ($aUserAvatars as $iSize => $sAvatarPath) { @unlink($this->Image_GetServerPath($sAvatarPath)); } } } else { $bError = true; $this->Message_AddError($this->Lang_Get('settings_profile_avatar_error'), $this->Lang_Get('error')); } } /** * Удалить аватара */ if (getRequest('avatar_delete')) { $this->User_DeleteAvatar($this->oUserCurrent); $this->oUserCurrent->setProfileAvatar(null); } /** * Загрузка фото, делаем ресайзы */ if (isset($_FILES['foto']) and is_uploaded_file($_FILES['foto']['tmp_name'])) { if ($sFileFoto = $this->User_UploadFoto($_FILES['foto'], $this->oUserCurrent)) { $this->oUserCurrent->setProfileFoto($sFileFoto); } else { $bError = true; $this->Message_AddError($this->Lang_Get('settings_profile_foto_error'), $this->Lang_Get('error')); } } /** * Удалить фото */ if (isset($_REQUEST['foto_delete'])) { $this->User_DeleteFoto($this->oUserCurrent); $this->oUserCurrent->setProfileFoto(null); } /** * Ставим дату последнего изменения профиля */ $this->oUserCurrent->setProfileDate(date("Y-m-d H:i:s")); /** * Сохраняем изменения профиля */ if (!$bError) { if ($this->User_Update($this->oUserCurrent)) { /** * Добавляем страну */ if ($this->oUserCurrent->getProfileCountry()) { if (!($oCountry = $this->User_GetCountryByName($this->oUserCurrent->getProfileCountry()))) { $oCountry = Engine::GetEntity('User_Country'); $oCountry->setName($this->oUserCurrent->getProfileCountry()); $this->User_AddCountry($oCountry); } $this->User_SetCountryUser($oCountry->getId(), $this->oUserCurrent->getId()); } /** * Добавляем город */ if ($this->oUserCurrent->getProfileCity()) { if (!($oCity = $this->User_GetCityByName($this->oUserCurrent->getProfileCity()))) { $oCity = Engine::GetEntity('User_City'); $oCity->setName($this->oUserCurrent->getProfileCity()); $this->User_AddCity($oCity); } $this->User_SetCityUser($oCity->getId(), $this->oUserCurrent->getId()); } $this->Message_AddNoticeSingle($this->Lang_Get('settings_profile_submit_ok')); } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error')); } } } }
/** * Executing parents move method and cleaning cache after it * * @access public * @param unknown_type $page * @param unknown_type $newParent * @param unknown_type $prevNode * @author Ultimate Module Creator */ public function move($page, $newParent, $prevNode = null) { Mage::getResourceSingleton('ibrams_cmsextended/page')->move($page->getId(), $newParent->getId()); parent::move($page, $newParent, $prevNode); $this->_afterMove($page, $newParent, $prevNode); }
/** * Get products count in category * * @param unknown_type $category * @return unknown */ public function getProductCount($category) { $productTable = AO::getSingleton('core/resource')->getTableName('catalog/category_product'); $select = $this->getReadConnection()->select(); $select->from(array('main_table' => $productTable), array(new Zend_Db_Expr('COUNT(main_table.product_id)')))->where('main_table.category_id = ?', $category->getId())->group('main_table.category_id'); $counts = $this->getReadConnection()->fetchOne($select); return intval($counts); }
/** * Обработка отправки формы при редактировании страницы * * @param unknown_type $oPageEdit */ protected function EventPagesEditSubmit($oPageEdit) { $this->Security_ValidateSendForm(); // * Проверяем корректность полей if (!$this->EventPagesCheckFields()) { return; } if ($oPageEdit->getId() == getRequest('page_pid')) { $this->_messageError($this->Lang_Get('system_error'), 'page:edit'); return; } // * Обновляем свойства страницы $oPageEdit->setAutoBr(getRequest('page_auto_br') ? 1 : 0); $oPageEdit->setActive(getRequest('page_active') ? 1 : 0); $oPageEdit->setMain(getRequest('page_main') ? 1 : 0); $oPageEdit->setDateEdit(date("Y-m-d H:i:s")); if (getRequest('page_pid') == 0) { $oPageEdit->setUrlFull(getRequest('page_url')); $oPageEdit->setPid(null); } else { $oPageEdit->setPid(getRequest('page_pid')); $oPageParent = $this->PluginPage_Page_GetPageById(getRequest('page_pid')); $oPageEdit->setUrlFull($oPageParent->getUrlFull() . '/' . getRequest('page_url')); } $oPageEdit->setSeoDescription(getRequest('page_seo_description')); $oPageEdit->setSeoKeywords(getRequest('page_seo_keywords')); $oPageEdit->setText(getRequest('page_text')); $oPageEdit->setTitle(getRequest('page_title')); $oPageEdit->setUrl(getRequest('page_url')); $oPageEdit->setSort(intval(getRequest('page_sort'))); $oPageEdit->setOtherUrl(getRequest('page_other_url')); // * Обновляем страницу if ($this->PluginPage_Page_UpdatePage($oPageEdit)) { $this->PluginPage_Page_RebuildUrlFull($oPageEdit); $this->_messageNotice($this->Lang_Get('page_edit_submit_save_ok'), 'page:edit'); $this->SetParam(0, null); $this->SetParam(1, null); } else { $this->_messageError($this->Lang_Get('system_error'), 'page:edit'); } }
/** * Define if a supply need is critical * * @param unknown_type $product * @param unknown_type $supplyNeed * @param unknown_type $pendingOrders */ public function IsCritical($product, $supplyNeed, $pendingOrders) { //supply need is critical if only this product is missing in an order if ($pendingOrders != null && Mage::getStoreConfig('purchase/supplyneeds/is_critical_if_order_only_missing_product') == 1) { //parse orders foreach ($pendingOrders as $order) { //parse order's products $otherProductsAreMissing = false; foreach ($order->getAllItems() as $OrderItem) { if ($OrderItem->getproduct_id() != $product->getId()) { $remainingQty = $OrderItem->getqty_ordered() - $OrderItem->getRealShippedQty() - $OrderItem->getreserved_qty(); if ($remainingQty < 0) { $otherProductsAreMissing = true; } } } if (!$otherProductsAreMissing) { return true; } } } return false; }
/** * Обработка редактирования топика * * @param unknown_type $oTopic * @return unknown */ protected function SubmitEdit($oTopic) { /** * Проверка корректности полей формы */ if (!$this->checkTopicFields()) { return false; } /** * Определяем в какой блог делаем запись */ $iBlogId = getRequest('blog_id'); if ($iBlogId == 0) { $oBlog = $this->Blog_GetPersonalBlogByUserId($oTopic->getUserId()); } else { $oBlog = $this->Blog_GetBlogById($iBlogId); } /** * Если блог не определен выдаем предупреждение */ if (!$oBlog) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'), $this->Lang_Get('error')); return false; } /** * Проверяем права на постинг в блог */ if (!$this->ACL_IsAllowBlog($oBlog, $this->oUserCurrent)) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'), $this->Lang_Get('error')); return false; } /** * Проверяем разрешено ли постить топик по времени */ if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) { $this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'), $this->Lang_Get('error')); return; } /** * Теперь можно смело редактировать топик */ $oTopic->setBlogId($oBlog->getId()); $oTopic->setTitle(getRequest('topic_title')); $oTopic->setText(htmlspecialchars(getRequest('topic_text'))); $oTopic->setTextShort(htmlspecialchars(getRequest('topic_text'))); $oTopic->setTextSource(getRequest('topic_text')); $oTopic->setLinkUrl(getRequest('topic_link_url')); $oTopic->setTags(getRequest('topic_tags')); $oTopic->setUserIp(func_getIp()); $oTopic->setTextHash(md5($oTopic->getType() . $oTopic->getText() . $oTopic->getLinkUrl())); /** * Проверяем топик на уникальность */ if ($oTopicEquivalent = $this->Topic_GetTopicUnique($this->oUserCurrent->getId(), $oTopic->getTextHash())) { if ($oTopicEquivalent->getId() != $oTopic->getId()) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_text_error_unique'), $this->Lang_Get('error')); return false; } } /** * Публикуем или сохраняем в черновиках */ $bSendNotify = false; if (isset($_REQUEST['submit_topic_publish'])) { $oTopic->setPublish(1); if ($oTopic->getPublishDraft() == 0) { $oTopic->setPublishDraft(1); $oTopic->setDateAdd(date("Y-m-d H:i:s")); $bSendNotify = true; } } else { $oTopic->setPublish(0); } /** * Принудительный вывод на главную */ if ($this->oUserCurrent->isAdministrator()) { if (getRequest('topic_publish_index')) { $oTopic->setPublishIndex(1); } else { $oTopic->setPublishIndex(0); } } /** * Запрет на комментарии к топику */ $oTopic->setForbidComment(0); if (getRequest('topic_forbid_comment')) { $oTopic->setForbidComment(1); } $this->Hook_Run('topic_edit_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog)); /** * Сохраняем топик */ if ($this->Topic_UpdateTopic($oTopic)) { $this->Hook_Run('topic_edit_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog, 'bSendNotify' => &$bSendNotify)); /** * Рассылаем о новом топике подписчикам блога */ if ($bSendNotify) { $this->Topic_SendNotifyTopicNew($oBlog, $oTopic, $this->oUserCurrent); } if (!$oTopic->getPublish() and !$this->oUserCurrent->isAdministrator() and $this->oUserCurrent->getId() != $oTopic->getUserId()) { Router::Location($oBlog->getUrlFull()); } Router::Location($oTopic->getUrl()); } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error')); return Router::Action('error'); } }
/** * Enter description here ... * * @param unknown_type $collection * @param unknown_type $attribute * @param unknown_type $range * @param unknown_type $index * @param unknown_type $tableName * @return Mage_CatalogIndex_Model_Resource_Price */ public function applyFilterToCollection($collection, $attribute, $range, $index, $tableName = 'price_table') { /** * Distinct required for removing duplicates in case when we have grouped products * which contain multiple rows for one product id */ $collection->getSelect()->distinct(true); $tableName = $tableName . '_' . $attribute->getAttributeCode(); $collection->getSelect()->joinLeft(array($tableName => $this->getMainTable()), $tableName . '.entity_id=e.entity_id', array()); $response = new Varien_Object(); $response->setAdditionalCalculations(array()); $collection->getSelect()->where($tableName . '.website_id = ?', $this->getWebsiteId())->where($tableName . '.attribute_id = ?', $attribute->getId()); if ($attribute->getAttributeCode() == 'price') { $collection->getSelect()->where($tableName . '.customer_group_id = ?', $this->getCustomerGroupId()); $args = array('select' => $collection->getSelect(), 'table' => $tableName, 'store_id' => $this->getStoreId(), 'response_object' => $response); Mage::dispatchEvent('catalogindex_prepare_price_select', $args); } $collection->getSelect()->where("(({$tableName}.value" . implode('', $response->getAdditionalCalculations()) . ")*{$this->getRate()}) >= ?", ($index - 1) * $range); $collection->getSelect()->where("(({$tableName}.value" . implode('', $response->getAdditionalCalculations()) . ")*{$this->getRate()}) < ?", $index * $range); return $this; }
/** * Generate product thumbnails * @param unknown_type $product */ public function generateThumb($product, $debug = false) { $thumsize = Mage::helper('solrsearch')->getSetting('autocomplete_thumb_size'); $width = 32; $height = 32; if (!empty($thumsize)) { $thumbSizeArray = explode('x', $thumsize); if (isset($thumbSizeArray[0]) && is_numeric($thumbSizeArray[0])) { if (isset($thumbSizeArray[1]) && is_numeric($thumbSizeArray[1])) { $width = trim($thumbSizeArray[0]); $height = trim($thumbSizeArray[1]); } } } $productId = $product->getId(); $image = trim($product->getSmallImage()); if (empty($image) || $image == 'no_selection') { $image = trim($product->getImage()); } if (empty($image) || $image == 'no_selection') { $productImagePath = Mage::helper('solrsearch/image')->getImagePlaceHolder(); } else { $productImagePath = Mage::getBaseDir("media") . DS . 'catalog' . DS . 'product' . DS . $image; } if (!file_exists($productImagePath)) { if ($product->getImage() != 'no_selection' && $product->getImage()) { $productImagePath = Mage::helper('solrsearch/image')->init($product, 'image')->resize($width, $height)->getImagePath(); if (!file_exists($productImagePath)) { $productImagePath = Mage::helper('solrsearch/image')->getImagePlaceHolder(); } } } $productImageThumbPath = Mage::getBaseDir('media') . DS . "catalog" . DS . "product" . DS . "sb_thumb" . DS . $productId . '.jpg'; if (file_exists($productImageThumbPath)) { unlink($productImageThumbPath); } $imageResizedUrl = Mage::getBaseUrl("media") . DS . "catalog" . DS . "product" . DS . "sb_thumb" . DS . $productId . '.jpg'; try { $imageObj = new Varien_Image($productImagePath); $imageObj->constrainOnly(FALSE); $imageObj->keepAspectRatio(TRUE); $imageObj->keepFrame(FALSE); $imageObj->backgroundColor(array(255, 255, 255)); //$imageObj->keepTransparency(TRUE); $imageObj->resize($width, $height); $imageObj->save($productImageThumbPath); } catch (Exception $e) { echo 'Exception at product[' . $productId . '][' . $productImageThumbPath . ']: ', $e->getMessage(), "\n"; } if (file_exists($productImageThumbPath)) { return true; } return false; }
/** * @param unknown_type $_deviceId * @param unknown_type $_class * @param unknown_type $_folderId * @return ActiveSync_Model_FolderState */ public function getFolderState($_deviceId, $_folderId) { $deviceId = $_deviceId instanceof ActiveSync_Model_Device ? $_deviceId->getId() : $_deviceId; // store current filter type $filter = new ActiveSync_Model_FolderStateFilter(array(array('field' => 'device_id', 'operator' => 'equals', 'value' => $deviceId), array('field' => 'folderid', 'operator' => 'equals', 'value' => $_folderId))); $folderStates = $this->_folderStateBackend->search($filter); if ($folderStates->count() == 0) { throw new Tinebase_Exception_NotFound('folderstate for device not found'); } return $folderStates->getFirstRecord(); }
/** * Обработка отправки формы при редактировании страницы * * @param unknown_type $oPageEdit */ protected function SubmitEditPage($oPageEdit) { /** * Проверяем корректность полей */ if (!$this->CheckPageFields()) { return; } if ($oPageEdit->getId() == getRequest('page_pid')) { $this->Message_AddError($this->Lang_Get('system_error')); return; } /** * Обновляем свойства страницы */ $oPageEdit->setActive(getRequest('page_active') ? 1 : 0); $oPageEdit->setAutoBr(getRequest('page_auto_br') ? 1 : 0); $oPageEdit->setMain(getRequest('page_main') ? 1 : 0); $oPageEdit->setDateEdit(date("Y-m-d H:i:s")); if (getRequest('page_pid') == 0) { $oPageEdit->setUrlFull(getRequest('page_url')); $oPageEdit->setPid(null); } else { $oPageEdit->setPid(getRequest('page_pid')); $oPageParent = $this->PluginPage_Page_GetPageById(getRequest('page_pid')); $oPageEdit->setUrlFull($oPageParent->getUrlFull() . '/' . getRequest('page_url')); } $oPageEdit->setSeoDescription(getRequest('page_seo_description')); $oPageEdit->setSeoKeywords(getRequest('page_seo_keywords')); $oPageEdit->setText(getRequest('page_text')); $oPageEdit->setTitle(getRequest('page_title')); $oPageEdit->setUrl(getRequest('page_url')); $oPageEdit->setSort(getRequest('page_sort')); /** * Обновляем страницу */ if ($this->PluginPage_Page_UpdatePage($oPageEdit)) { $this->PluginPage_Page_RebuildUrlFull($oPageEdit); $this->Message_AddNotice($this->Lang_Get('plugin.page.edit_submit_save_ok')); $this->SetParam(0, null); $this->SetParam(1, null); } else { $this->Message_AddError($this->Lang_Get('system_error')); } }
/** * Обработка отправленого пользователю приглашения вступить в блог */ protected function EventInviteBlog() { require_once Config::Get('path.root.engine') . '/lib/external/XXTEA/encrypt.php'; $sCode = xxtea_decrypt(base64_decode(rawurldecode(getRequest('code'))), Config::Get('module.blog.encrypt')); if (!$sCode) { return $this->EventNotFound(); } list($sBlogId, $sUserId) = explode('_', $sCode, 2); $sAction = $this->GetParam(0); /** * Получаем текущего пользователя */ if (!$this->User_IsAuthorization()) { return $this->EventNotFound(); } $this->oUserCurrent = $this->User_GetUserCurrent(); /** * Если приглашенный пользователь не является авторизированным */ if ($this->oUserCurrent->getId() != $sUserId) { return $this->EventNotFound(); } /** * Получаем указанный блог */ if (!($oBlog = $this->Blog_GetBlogById($sBlogId)) || $oBlog->getType() != 'close') { return $this->EventNotFound(); } /** * Получаем связь "блог-пользователь" и проверяем, * чтобы ее тип был INVITE или REJECT */ if (!($oBlogUser = $this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(), $this->oUserCurrent->getId()))) { return $this->EventNotFound(); } if ($oBlogUser->getUserRole() > ModuleBlog::BLOG_USER_ROLE_GUEST) { $sMessage = $this->Lang_Get('blog_user_invite_already_done'); $this->Message_AddError($sMessage, $this->Lang_Get('error'), true); Router::Location(Router::GetPath('talk')); return; } if (!in_array($oBlogUser->getUserRole(), array(ModuleBlog::BLOG_USER_ROLE_INVITE, ModuleBlog::BLOG_USER_ROLE_REJECT))) { $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'), true); Router::Location(Router::GetPath('talk')); return; } /** * Обновляем роль пользователя до читателя */ $oBlogUser->setUserRole($sAction == 'accept' ? ModuleBlog::BLOG_USER_ROLE_USER : ModuleBlog::BLOG_USER_ROLE_REJECT); if (!$this->Blog_UpdateRelationBlogUser($oBlogUser)) { $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'), true); Router::Location(Router::GetPath('talk')); return; } if ($sAction == 'accept') { /** * Увеличиваем число читателей блога */ $oBlog->setCountUser($oBlog->getCountUser() + 1); $this->Blog_UpdateBlog($oBlog); $sMessage = $this->Lang_Get('blog_user_invite_accept'); } else { $sMessage = $this->Lang_Get('blog_user_invite_reject'); } $this->Message_AddNotice($sMessage, $this->Lang_Get('attention'), true); Router::Location(Router::GetPath('talk')); }
/** * Рассылает уведомления о новом топике подписчикам блога * * @param unknown_type $oBlog * @param unknown_type $oTopic * @param unknown_type $oUserTopic */ public function SendNotifyTopicNew($oBlog, $oTopic, $oUserTopic) { $aBlogUsersResult = $this->Blog_GetBlogUsersByBlogId($oBlog->getId(), null, null); // нужно постранично пробегаться по всем $aBlogUsers = $aBlogUsersResult['collection']; foreach ($aBlogUsers as $oBlogUser) { if ($oBlogUser->getUserId() == $oUserTopic->getId()) { continue; } $this->Notify_SendTopicNewToSubscribeBlog($oBlogUser->getUser(), $oTopic, $oBlog, $oUserTopic); } //отправляем создателю блога if ($oBlog->getOwnerId() != $oUserTopic->getId()) { $this->Notify_SendTopicNewToSubscribeBlog($oBlog->getOwner(), $oTopic, $oBlog, $oUserTopic); } }