вторник, 15 ноября 2011 г.

Drupal. Отправка уведомлений о днях рождения друзей

Данный код использует модули ur_relationships и privatemsg. Сам код вставляется в действе rule, которое реагирует на событие залогинивания пользователя.

$account->uid, 'rtid' => $active_relationships, 'approved' => TRUE));

// Создаем массив с ID друзей
// We have to do this if() twice because we could
// be a requester or a requestee, and we never know which.
$friends = array();
$users_birthday = array();
foreach ($relationships as $relationship) {
if ($account->uid == $relationship->requester_id) {
$friends[$relationship->requestee_id] = array();
}
if ($account->uid == $relationship->requestee_id) {
$friends[$relationship->requester_id] = array();
}
}
// Finally, we load content profiles for our selected type
// and for our friends from the array above.
// Загружаем Материалы с профилями пользователей
foreach (array_keys($friends) as $friend_uid) {
$friend_profile = content_profile_load($profile_type, $friend_uid);
$friend_birthdate = $friend_profile->$birthday_field;
$friend_birthday = date('m-d', strtotime($friend_birthdate[0]['value']));

// Если дата рождения пользователя находится между датой последнего логина и $birthday(сегодня +1 день),
// то добавляем данные пользователя в массив $users_birthday
if($users_last_login_date_str<=$friend_birthday && $friend_birthday<=$birthday){ $user_birthday = user_load($friend_uid); $users_birthday[$friend_uid]['uid']=$friend_uid; //$users_birthday[$friend_uid]['birthdate']=$friend_birthdate[0]['value']; $users_birthday[$friend_uid]['birthdate'] = date('d-m-y', strtotime($friend_birthdate[0]['value'])); $users_birthday[$friend_uid]['fio']=$friend_profile->field_first_name_profile[0]['value'] . ' ' . $friend_profile->field_last_name_profile[0]['value'] . ' ' . $friend_profile->field_middle_name_profile[0]['value'] ;
}
}

// Если есть пользователи у которых было или будет Д.Р. в указанном промежутке дат, то шлем текущему пользователю сообщение об этом
if (!empty($users_birthday)) {
//----------------- send message --------------------------------
$index_sql = "INSERT INTO {pm_index} (mid, thread_id, uid, is_new, deleted) VALUES (%d, %d, %d, %d, 0)";
// 1) Save the message body first.
$args = array();
//$args[] = $message['subject']; // Тема сообщения
$args[] = "Дни Рождения.";
//$args[] = $message['author']->uid; // ID Отправляющего
$args[] = 1;
//$args[] = $message['body']; // Тело сообщения
$temp_body="

Здравствуйте!

Уведомляем Вас о облизжайших Днях Рождения ваших контактов:

";
foreach($users_birthday as $tub)
{
$tdob = $tub['birthdate'];// format_date($tub['birthdate'], $type = 'custom', $format = 'd-m-y')
$temp_body.= '

Дата: '. $tdob . ' ' . ''. $tub['fio'].''.'

';
///view_another_user_profile/61
//...
}
$args[] = $temp_body;
//$args[] = $message['format'];// Формат сообщения
$args[] = 2;
//$args[] = $message['timestamp']; // Время отправки
$args[] = time();
$message_sql = "INSERT INTO {pm_message} (subject, author, body, format, timestamp) VALUES ('%s', %d, '%s', %d, %d)";
db_query($message_sql, $args);
$mid = db_last_insert_id('pm_message', 'mid');
$message['mid'] = $mid;

// Thread ID is the same as the mid if it's the first message in the thread.
if (!isset($message['thread_id'])) {
$message['thread_id'] = $mid;
}

// 2) Save message to recipients.

db_query($index_sql, $mid, $message['thread_id'], $user->uid, 1);

// When author is also the recipient, we want to set message to UNREAD.
// All other times the message is set to READ.
$is_new = isset($message['recipients'][$message['author']->uid]) ? 1 : 0;

// Also add a record for the author to the pm_index table.
if (!db_query($index_sql, $mid, $message['thread_id'], $message['author']->uid, $is_new)) {
return FALSE;
}
}

?>

Drupal Печать формы из Views Php CustomField

Для того, чтобы напечатать форму из нужного нам views, нужно создать поле Php типа CustomField и в нем написать следующий php код.

$user->uid,
'name' => (isset($user->name) ? $user->name : ''),
'type' => $node_type,
);
// Invoke hook_nodapi and hook_node
node_object_prepare($node);

// Можно использовать уже существующую ноду, например
// $node = node_load(123);
// отображаем форму:
$output = drupal_get_form($form_id, $node);

print $output;

error_reporting(1);
?>



// $node_type -Тип ноды

C# MemoryOutExeption при использовании Image.FromStream и при закрытии MemoryStream

Конструкция

public static Image GetImage(byte[] data) {

if (data == null) return null;

MemoryStream ms = new MemoryStream(data);

Image img = Image.FromStream(ms);

// closing the stream later crashes the application

// ms.Close(); // => memory leak

return img;

}

при перерисовке изображения создаст OUT OF MEMORY exception.

Если закрывать MemoryStream, то будет memory leak



Для решения проблемы нужно использовать следующий фрагмент

Image img = Image.FromStream(ms);

Image ReturnMe = (Image)img.Clone();

img = null;

ms.close();



Рабочий вариант:

public static Image GetImage(byte[] data) {

if (data == null) return null;

MemoryStream ms = new MemoryStream(data);

Image img = Image.FromStream(ms);

Image ReturnMe = (Image)img.Clone();

img = null;

ms.close();

return ReturnMe;

}