Автор Анна Евкова
Преподаватель который помогает студентам и школьникам в учёбе.

Устройство персонального компьютера (Основные принципы работы персональных компьютеров)

Содержание:

Введение

Выпуск компьютеров IBM PC был начат в 1981 году, и они быстро завоевали огромную популярность у пользователей. IBM PC и совместимые с ними компьютеры составляют теперь большую часть парка профессиональных ПЭВМ в мире. В настоящее время программное обеспечение, разработанное для IBM PC, охватывает практически все сферы человеческой деятельности. Персональный компьютер включает в себя следующие устройства: процессор, выполняющий управление компьютером, вычисления и т.д.; клавиатуру, позволяющую вводить символьную информацию в компьютер; монитор (или дисплей) для изображения текстовой и графической информации; накопители для гибких магнитных дисков, используемые для чтения и записи информации на гибкие магнитные диски; накопитель на жестком магнитном диске, предназначенном для чтения и записи информации на несъемный жесткий магнитный диск. Кроме того к компьютеру могут подключаться принтер - для вывода на печать текстовой и графической информации; мышь - устройство, облегчающее ввод информации в компьютер, и другие манипулирующие устройства.

Цель данной работы - рассмотреть устройство и основные принципы работы компьютера.

Объект исследования - персональный компьютер.

Предмет исследования - устройство персонального компьютера.

Для реализации цели работы необходимо решить следующие задачи:

- рассмотреть строение компьютера;

- определить особенности работы компьютера;

- выявить проблемы в устройстве компьютера.

Методы исследования: анализ литературных и интернет источников по теме исследования.

1. Устройство компьютера

Компьютер, в обыденном понимании, состоит из системного блока, монитора, компьютерной клавиатуры, мышки, аудиоколонок и другого оборудования. О функциях монитора, клавиатуры, мышки и др., думаю, говорить не стоит - все очевидно.

Самой главной, сложной и дорогостоящей частью компьютера является системный блок. Собственно, системный блок (в классическом понимании) и является компьютером. Остальное оборудование предназначено лишь для ввода и вывода информации в различной форме и обеспечения управления системой. Т.е., если к системному блоку присоединить более современный монитор, клавиатуру или мышь, станет просто удобней смотреть фильмы, работать с текстом или играть, но возможности компьютера от этого не улучшатся. Все процессы, отображаемые на мониторе, происходят внутри системного блока и именно устройствами, находящимися в нем, определяется производительность (мощность) компьютерной системы.

Устройство компьютера (системного блока): материнская плата, процессор, оперативная память, постоянное запоминающее устройство, видеокарта.

Основой любого современного компьютера (системного блока) является материнская плата (главная плата, англ. motherboard, MB, mainboard, разг. – мамка, материнка, мать и др.) - плата, к которой подсоединяются основные компоненты компьютера: центральный процессор, оперативная память, видеокарта, жесткий диск, оптический привод и др. На ней же размещены USB и другие разъемы для подключения оборудования (см. рис.). Главная задача материнской платы – соединить все эти компоненты и заставить их работать как единое целое – компьютер. Материнскую плату невозможно не заметить, если открыть крышку системного блока.

Процессор (центральный процессор, CPU) – сердце компьютера (см. рис.). Он исполняет все команды пользователя и «руководит» остальным «железом». От его мощности зависит быстродействие компьютера и его возможности. На материнской плате процессор крепится в специальном разъёме, называемом разъёмом центрального процессора или сокетом (socket). Есть несколько видов сокетов, в каждый из которых можно установить только процессоры определенного типа (с таким-же разъёмом). Т.е., на материнскую плату с Socket 775 можно установить только процессоры Intel Pentium, Celeron, Core 2 Duo, Core 2 Quadro и др. с разъёмом 775. Для процессоров AMD (Athlon, Phenom и др.) понадобится материнская плата с сокетом AM3, и т.д.

Сверху установленного на материнской плате процессора крепится охлаждение. Чаще всего, оно являет собой небольшой радиатор с вентилятором (куллером) для рассеивания тепла (см.рис.). Без охлаждения процессор будет быстро перегреваться. При достижении им критической температуры компьютер выключается. Пока процессор не остынет, включить его снова не получится. Перегрев процессора возможен также при засорении радиатора охлаждения пылью. Для устранения проблемы обычно достаточно очистить его при помощи бытового пылесоса или другим способом. Для профилактики, «уборку» системного блока от пыли полезно производить периодически (раз в несколько месяцев).

Рисунок 1 - Устройство процессора

В устройство компьютера обязательно входят модули ОЗУ (оперативного запоминающего устройства, см.рис.1). Это составная часть компьютера, в которой временно хранятся данные, необходимые процессору для выполнения им операций. После завершения таких операций (например, закрытия программы) связанные с ними данные из оперативной памяти удаляются. При запуске новых задач (программ) в ОЗУ с жесткого диска подгружаются данные, необходимые процессору в этот момент. Скорость доступа к информации, находящейся в оперативной памяти, в сотни раз выше скорости доступа к жесткому диску. Это позволяет процессору оперировать нужной информацией, получая к ней практически мгновенный доступ.

Оперативная память бывает нескольких видов. На момент написания этой статьи, самым современным и быстрым ОЗУ был DDR III, хотя чуть более медленный DDR II по-прежнему не сдает свои позиции и уже несколько лет является достаточно распространенным.

На производительность компьютера влияет не только скорость (тип) ОЗУ, но и его объём. Если для выполнения определенных задач процессору будет недостаточно объёма оперативной памяти, для ее расширения он использует часть жесткого диска (так называемый файл подкачки, или своп-файл (swap). Учитывая, что скорость доступа к жесткому диску значительно ниже скорости доступа к ОЗУ, компьютер будет страшно «тормозить».

Каждый тип модулей ОЗУ имеет свой разъем. Поэтому на материнскую плату, рассчитанную на поддержку ОЗУ DDR II, модуль DDR III поставить нельзя никак (даже физически в слот он не войдет).

Устройство компьютера предусматривает также наличие жесткого диска (винчестера, см. рис.1) – запоминающего устройство, на котором хранится вся информация, имеющаяся в компьютере. Чем больше объем винчестера, тем больше на нем можно хранить разного рода файлов. Современные жесткие диски присоединяются к материнской плате через интерфейс SATA (см.рис.1). Винчестеры больших объемов могут перегреваться и нуждаются в охлаждении (как правило, небольшого куллера достаточно).

Вместо жестких дисков или вместе с ними на компьютерах все чаще используються SSD - быстрые запоминающие устройства на основе микросхем памяти.

Видеокарта (видеоадаптер, графический адаптер, графический процессор, GPU) – часть компьютера, отвечающая за скорость обработки видеоинформации (см. рис.). Современные видеокарты подсоединяются к разъему PCI-Express материнской платы. Некоторые материнские платы имеют несколько разъёмов PCI-Express. Это позволяет одновременно использовать несколько видеокарт, что делает графическую подсистему компьютера более мощной.

В некоторых случаях материнские платы имеют интегрированный (встроенный) графический адаптер. Его возможностей вполне достаточно для офисной работы, т.е. обработки текста, просмотра страниц Интернета, видео, фотографий и даже игры в несложные игры (типа пасьянс «Косынка» или «Солитер»). Более мощная видеоподсистема нужна либо профессионалам, работающим с графикой, либо любителям поиграть в игрушки покруче.

Видеоадаптер может быть интегрирован и в центральный процессор. Без отдельной видеокарты в таком случае также можно обойтись.

Отдельная мощная видеокарта в компьютере любителя поиграть гораздо предпочтительней производительного центрального процессора. Процессор среднего уровня и хорошая видеокарта в играх оставят далеко позади самый современный процессор с интегрированным видеоадаптером. В то же время, для выполнения других задач (архивирование файлов, перекодирование видео, аудио, работа в Фотошопе и др.) мощный процессор нужней. Необходимо также учитывать, что слишком слабый процессор не даст возможности видеокарте раскрыть весь свой потенциал. Здесь важен баланс.

В устройство компьютера, как правило, входят также сетевая и звуковая карты, разъемы для подсоединения оптического (для записи/чтения CD и DVD) и других приводов, размещенные на материнской плате. Для расширения возможностей компьютера в разъёмы РCI (см. рис.1) можно поставить несколько типов устройств (модемы, ТВ-тюнеры, Wi-Fi-адаптеры, звуковые карты, сетевые карты и др.).

Само собой, для работы всего вышеупомянутого «железа» нужен блок питания. Его мощность должна удовлетворять аппетиты процессора, видеокарты и других «потребителей электричества».

2. Основные принципы работы персональных компьютеров

Персональный компьютер (ПК) - это электронное устройство, предназначенное для обработки информации. Компьютеры отличаются от других устройств по обработке информации тем, что они выполняют все свои действия под управлением программ.

Программа - это подробное задание компьютеру.

Существует единица измерения информации, обрабатываемой ПК – это байт. Под байтом понимается один символ (буква, цифра, знак препинания и т.д.:). Каждый байт состоит из 8 битов. Комбинация битов и дает разнообразные символы. На основе байта различают следующие единицы измерения информации:

1 КБ (килобайт) = 1024 байта;

1 МБ (мегабайт) = 1024 КБ;

1 ГБ (гигабайт) = 1024 МБ

1 ТБ (терабайт) = 1024 ГБ

Одна страница печатного текста равна приблизительно 2,5 КБ. Современный персональный компьютер состоит, в основном, из процессора, дисплея и клавиатуры. Можно дополнительно присоединять принтер, манипуляторы (мышь и джойстик), сетевые и звуковые платы, модемы, сканеры и т. д. В конечном счете, собственно компьютер как вычислительный операционный агрегат со своими хранилищами информации сосредоточен в процессоре. Клавиатура нужна для получения указаний пользователя. Ответы на указания выводятся на дисплей или экран.

Комплектация ПК из различных устройств создает разнообразную конфигурацию компьютеров.

Рассмотрим назначение и функции различных устройств, входящих в компьютер или подключаемых к нему.

Процессор персонального компьютера - самый главный элемент компьютера. Процессор читает команды, записанные в памяти компьютера и выполняет их.

Процессор содержит:

Основной микропроцессор, который выполняет вычисления и управляет работой всех устройств ПК.

Основной микропроцессор определяет быстродействие (тактовую частоту) или производительность персонального компьютера. Тактовая частота измеряется в мегагерцах (МГц). Количество мегагерц процессора примерно соответствует количеству элементарных операций, выполняемых процессором за одну секунду. Сегодня распространены следующие виды микропроцессоров:

INTEL 80486 (с тактовой частотой от 33 до 80 МГц)

INTEL 80586 Pentium (с тактовой частотой от 66 до 220 МГц)

INTEL Pentium II (с тактовой частотой от 300 до 600 МГц)

INTEL Pentium III (с тактовой частотой от 600 до 900 МГц)

INTEL Pentium IV (с тактовой частотой от 1000 до 2200 МГц)

AMD (с тактовой частотой от 800 до 2400 МГц)

CYRIX (с тактовой частотой от 700 до 1800 МГц)

Среди вышеперечисленных процессоров, Pentium IV считается наиболее надежным и быстродействующим процессором за счет применения ряда современных и уникальных технологических достижений. Но в тоже время эта марка процессора, выпускаемая фирмой INTEL является наиболее дорогостоящей.

На корпусах старых компьютеров с процессорами от 80286 до 80586 была установлена кнопка с надписью Turbo. При наличии таких компьютеров у Вас в эксплуатации необходимо помнить, что эта кнопка должна всегда быть в активном состоянии (горящая лампочка) - что обеспечивает наибольшую тактовую частоту (скорость работы) процессора.

Значение тактовой частоты на старых компьютерах высвечивается на цифровой индикаторной панели. Иногда высвечиваются латинские буквы HI (режим Turbo активен) или LO (режим Тurbo отключен).

По умолчанию, режим ТиrЬо включен. Термин по умолчанию используется для обозначения состояния первоначальной настройки компьютера или программы.

Основной микропроцессор может выполнять любые вычисления. Но при выполнении вычислений с большой точностью, т.е. с плавающей точкой, происходит некоторое замедление скорости выполнения расчетов. Наличие математического сопроцессора увеличивает скорость выполнения таких расчетов от 5 до 15 раз.

На новых компьютерах с процессорами Pentium II, III и IV математические сопроцессоры встроены в основные процессоры. На старых же компьютерах математические сопроцессоры были установлены в виде отдельной микросхемы. Эти сопроцессоры выполняют специальные команды обработки чисел с плавающей точкой.

В оперативной памяти или в оперативном запоминающим устройстве (ОЗУ) компьютера располагаются наборы команд для процессора, называемые программами, а также обрабатываемые компьютером данные.

Память компьютера – это структура, созданная на кремниевой плате. Она состоит из набора ячеек, каждая из которых хранит минимум данных.

Компьютер загружает в оперативную память программы и необходимые данные. Процессор поочередно выбирает из оперативной памяти команды программы и выполняет их.

Процессор может непосредственно работать только с оперативной памятью. При выключении компьютера вся информация, содержащаяся в оперативной памяти, пропадает бесследно.

Различают основную и расширенную оперативную память.

Размер основной оперативной памяти -1 МБ. Она состоит из двух частей:

- 640 КБ используются операционной системой и другими системными программами, такими как драйверы устройств и комплектующих компьютера;

- остальная часть основной памяти используется резидентными программами, контролирующими работу устройств компьютерах.

Расширенная память – это часть оперативной памяти сверх первого мегабайта, которая используется под прикладные программы. Эту часть оперативной памяти можно расширять практически беспредельно. На современных компьютерах минимальный объем оперативной памяти составляет 128 МБ. Максимальный объем ОЗУ персонального компьютера может достигать 8 ГБ.

Электронные схемы (контроллеры), управляющие работой различных устройств, входящих в состав компьютер (дисплей, дисковод...).

Порты ввода-вывода, через которые процессор обменивается данными с внешними устройствами.

Клавиатура используется для ввода текстовой информации. Как правило, компьютер снабжен русско/латинской клавиатурой со 101 клавишей. Почти все клавиши, независимо от того, что на них написано, не вызывают какой-либо определенной реакции компьютера, а обрабатываются программами. Рассмотрим расположение клавиш на клавиатуре.

В центре клавиатуры находится клавиша Enter. Она самого большого размера. Именно этой клавишей пользователь дает согласие на выполнение той или иной операции.

В левом верхнем углу клавиатуры находится клавиша Esc, прямая противоположность предыдущей. Это клавиша отказа от команды или ситуации на экране.

Направо от клавиши Esc находятся функциональные клавиши. На стандартной клавиатуре расположено двенадцать функциональных клавиш от F1 до F12. Большинство программ работает только с десятью функциональными клавишами, оставляя F11 и F12 свободными.

Функциональные клавиши выполняют различные действия (операции). В старых программах эти действия функциональных клавиш завысили от конкретной программы. В современных клавишах за каждой функциональной клавишей закреплено конкретное действие, которое распространяется на все прикладные программы. Так например, за клавишей F1 закреплена функция помощи. Если для программы установлен пояснительный текст, то он вызывается по клавише F1.

Под клавишей Esc и функциональными клавишами находится буквенно-цифровой блок клавиатуры. В этом блоке клавиши расположены точно также как на пишущей машинке.

При чем, в распоряжение пользователя предоставлены как латинские буквы (латиница), так и русские буквы (кириллица),

По умолчанию, пользователь получает в свое распоряжение кириллицу. Латиницу можно использовать только после нажатия определенной комбинации клавиш. Нажатие любой буквенной клавиши выводит строчную (маленькую) букву. Для получения прописной (заглавной) буквы, необходимо удерживая клавишу Shift нажать буквенную клавишу.

На некоторых клавишах буквенно-цифрового блока нарисовано по два символа сверху и снизу. Снизу нарисованы символы нижнего регистра. Они выводятся по умолчанию. В комбинации с клавишей Shift выводятся символы верхнего регистра.

Если нужно долго набирать прописные буквы, то все время держать начатой клавишу Shift нет необходимости. Специальная клавиша Caps Lock (переводит клавиатуру в режим верхнего регистра. Каждое нажатие клавиши Caps Lock переводит клавиатуру в режим верхнего или нижнего регистра, Если режим верхнего регистра включен, в правой части клавиатуры горит индикаторная лампочка. При повторном нажатии на клавишу Caps Lock лампочка гаснет, режим верхнего регистра отключается.

Клавиша Tab при вводе текста заставляет курсор сделать отступ сразу на несколько позиций - это клавиша табуляции. Если на экране присутствует несколько объектов, клавиша Tab используется для перехода с объекта на объект.

В нижнем ряду буквенно-цифрового блока находится самая длинная клавиша - это клавиша пробел. Справа и слева от нее расположены клавиши Alt.. Они используются только в комбинации с другими клавишами. Часто левая и правая клавиши Alt равнозначны. Если важно какую клавишу нажимать, это обязательно указывается.

Слева и справа от клавиши Alt находится клавиша Ctrl. Этой клавише соответствует сокращенное обозначение -^. Клавиша Ctrl(^), также как и клавиша Alt, используется в комбинации с другими клавишами.

Над клавишей Enter находится клавиша BackSpace (BS) иногда на этой клавише нарисована лишь стрелка влево. Клавиша BackSpace удаляет символ слева от текущего.

Направо от функциональных клавиш находится специальный блок, который содержит три клавиши: PrintScreen – вывод на печать текущего образа экрана, ScrollLock – переключение режима вывода информации, NumLock – переключение дополнительного блока, находящегося в правой части клавиатуры, то в цифровой режим, то в управляющий.

К клавишам управления, в первую очередь, относятся стрелки вверх, вниз, влево и вправо. Стрелки влево и вправо осуществляют перемещение на один символ влево или вправо соответственно. Клавиши стрелка вверх и вниз осуществляют перемещение на одну строку вверх или вниз. Клавиши Home и End осуществляют перемещение в начало или конец чего-либо.

Клавиши Page UP и Page Down - клавиши листания информации, если есть что листать. Клавиша Page UP "листает" информацию вверх, а клавиша Page Down - вниз.

Клавиша Insert связана со вставкой или отметкой чего-либо. Клавиша Delete удаляет текущий символ.

В правой части клавиатуры находится дополнительный блок. В этом блоке находятся дубли клавиш управления курсором или дубли клавиш цифр. На старых клавиатурах в левом верхнем углу этого блока находится клавиша NumLock. Действия этой клавиши были описаны выше.

Если индикаторная лампочка над клавишей NumLock горит, то это обозначает цифровой режим. Данная часть клавиатуры в цифровом режиме может быть удобна для пользователей привыкших работать на калькуляторе. Для окончательного удобства рядом размещен дубль клавиши Enter.

Клавиши плюс, минус, звездочка окрашены в серый цвет. Программы используют их для выполнения некоторых операций, В этом случае клавиши называют по цвету: серый плюс, серый минус и серая звездочка.

Клавиатура отнюдь не представляет собой лишь контактную доску с кнопками. Это устройство с собственным управляющим процессором (контроллером). Он отслеживает нажатие любой клавиши в темпе, значительно превышающем скорость работы самой быстрой машинистки.

Для каждой клавиши контроллер формирует свои числа - номера событий (их называют скан-кодами, от слова "сканировать" просматривать).

Системное программное обеспечение преобразует скан-коды и их последовательности в коды символов согласно символьной таблицы соответствующего языка. Затем эти коды помещаются в так называемый кольцевой буфер клавиатуры. В свою очередь прикладные программы считывают коды символов из кольцевого буфера клавиатуры, выводят их на дисплей (монитор) компьютера, или же направляют на процессор для выполнения какой-либо программы.

Кольцевой буфер клавиатуры - это временное хранилище на 15 кодов (символов).

Пользователь, нажимая клавиши в любом темпе, помещает туда коды, а программа их считывает в том темпе, в котором может.

Если буфер "забит" кодами, которые программа не успевает считывать, то запись в буфер приостанавливается. На каждый вновь приходящий код компьютер отвечает тревожным гудком встроенного динамика.

Дисплей (экран или монитор) предназначен для вывода текстовой и графической информации. Дисплеи бывают: цветные и монохромные. Современные дисплеи, в основном, цветные.

Дисплей может работать в одном из двух режимов текстовом и графическом. В настоящее время текстовой режим дисплея практически не применяется.

Изображение на экране формируется графическим адаптером, который еще называют контроллером дисплея, видеокартой, графической платой или графическим контроллером.

Для современных графических программ большое значение имеет разрешающая способность графического контроллера. Любое изображение на дисплеи формируется за счет разноцветных точек, составляющих изображение в виде мозаики. Разрешающая способность – это количество точек по горизонтали и по вертикали дисплея. Тем больше точек может отобразиться по горизонтали и вертикали дисплея, и тем больше цветов будет у этих точек, тем более четким и реалистичным будет изображение на экране компьютера.

На дисплее находится специальный регулятор яркости со знаком "солнышко". Регулятор позволяет установить яркость соответствующую наиболее комфортной работе пользователя.

HDD - скоростной жесткий магнитный диск, который предназначен для постоянного хранения информации. Современные жесткие диски имеют объем от 20 Гб (Гигабайт) до 4 Тб (Терабайт).

На корпусе компьютера находится крошечное индикатор, который подсвечивается в те моменты, когда процессор обращается к накопителю на жестком магнитном диске. Надпись HDD (Hard Disk Drive) означает - дисковод жесткого диска. Слово "Drive" связывается с понятием «накопитель на дисковых устройствах» и зачастую переводится как "устройство" или "диск". Термин диск обозначает не только физически единый накопитель, но и условные «логические» накопители информации, на которые можно разделить большой жесткий диск.

Винчестером жесткий диск начали называть с 1973 года. В этом году компания IBM выпустила жесткий диск, на котором могли храниться 30 блоков информации на 30 дорожках. Сокращенно он назывался "30/З0", что совпадало с калибром популярного охотничьего оружия “Winchester”

Диски принято обозначать буквами английского алфавита с обязательным двоеточием после буквы. Так А: и В: зарезервированы для обозначения дискет. Если на ПК установлен только один дисковод, то буква В: не задействована. Обозначение логических дисков винчестера всегда начинается с буквы С:.

Дисковод (FDD) – узкий щелевой проем, в который вставляется накопитель на гибком магнитном диске или дискета. Обозначение FDD (Floppy Disk Drive) переводится как дисковод гибкого магнитного диска или дискеты.

Дискеты служат для того, чтобы можно было переносить информацию с одного компьютера на другой. А также сохранять на них информацию, которая не нужна постоянно. На дискетах часто хранят дубли документов и отчетов, которые очень важны и должны уцелеть при любых сбоях на ПК.

Каждому размеру дискеты соответствует свой дисковод. Если дисковод один, то чаще это дисковод для дискет на 3,5 дюйма. Дисководы и соответственно дискеты на 5,25 дюймов сейчас практически не применяются. На смену этим дисководам пришли так USB-разъемы, которые дают возможность применять съемные носители информации объемом до 32 Гб.

Мышь – манипулятор для выбора информации на экране. Это маленькая коробочка с двумя или тремя кнопками. Вместе с проводом для подключения к ПК это устройство действительно напоминает мышь. Перемещение мыши по гладкой поверхности приводит к перемещению по экрану курсора мыши. Собственно говоря, по гладкой поверхности катается шарик, Его можно увидеть, перевернув мышь.

Иногда в тех же целях используется манипулятор trackball или манипулятор колобок. Фактически, trackball – это мышь наоборот. В таком манипуляторе катают шарик пальцами для перемещения курсора на экране.

СD-RОМ дисковод для компакт-дисков, который работает только в режиме чтения. Компакт-диск передает данные со значительно меньшей скоростью, чем жесткий диск. Но, в тоже время компакт-диск может хранить до 900 МБ информации и легко переноситься с компьютера на компьютер. В наше время все большее распространение получают так называемые CD-RW дисководы для компакт-дисков. Эти дисководы производят не только чтение компакт-дисков, но и запись информации на эти диски. Запись на компакт-диски можно производить ограниченное число раз. Сейчас пока еще более распространены компакт-диски с одноразовой записью.

Практически все производители программного обеспечения распространяют свои программы на компакт-дисках. На этих дисках выпускается огромное количество программных приложений, игр и справочников.

В работе с СD-RОМ играет большую роль скорость передачи данных, которая может варьироваться от 150 до 2250 КБ в секунду. Для приемлемой работы аудиовизуальных приложений необходима скорость не менее 1200 КБ в секунду.

Локальные шины PCI и USB позволяют периферийным устройствам полностью воспользоваться производительностью работы центрального процессора, независимо от его тактовой частоты и архитектуры. Мощный процессор, работающий на высокой частоте, вынужден ждать пока периферийные устройства обменяются с ним данными. Чтобы исключить несовместимость скорости работы процессора со скоростью обмена данными компьютера с периферийными устройствами и обеспечить наиболее эффективную работу для систем с процессором Pentium, компания 1п1е1 разработала спецификацию локальных шин PCI и USB.

Принтер – устройство вывода информации на бумагу или на другой твердый носитель (ткань, пленка и т.д.). В зависимости от принципа вывода информации на печать, принтеры бывают: матричные, струйные, лазерные и т. п. Матричные и лазерные принтеры в основном черно-белые, но бывают и цветные. Струйные принтеры как правило цветные.

В матричных или точечно-матричных принтерах информацию на печать выводит печатающая головка принтера, которая содержит металлические стержни или иголки. Головка движется вдоль печатаемой строки, а стержни в нужный момент ударяют по бумаге через красящую ленту.

В струйных принтерах изображение формируется микро каплями особых чернил, выдуваемых на бумагу с помощью специальных сопел.

Лазерные принтеры обеспечивают высокое качество печати. В этих принтерах для печати используется принцип ксерографии.

Джойстик – манипулятор в виде укрепленной на шарнире ручки с кнопкой. Джойстик используется в компьютерных играх.

Дигитайзер позволяет преобразовать графическую информацию (чаще чертежи) в цифровую форму. Используется в конструкторских бюро.

Графопостроитель или плоттер выводит чертежи на бумагу. Чертежи можно выводить и на лазерном принтеры, но плоттер или графопостроитель дешевле.

Сканер – устройство для ввода графической и текстовой информации в компьютер. Сканер преобразует картинки в графические файлы. Сканер бывает настольный и ручной. Настольный сканер надежнее.

SoundBlaster или звуковая карта совместно с колонками или наушниками дает возможность исполнять музыку. Без этой приставки компьютер может выводить в каждый момент звук только одного тона.

Сетевой адаптер или сетевая карта позволяет подключить компьютер в локальную сеть. Благодаря этой сети со своего компьютера можно получить быстрый доступ к данным других компьютеров, объединенных в сеть коаксиальным кабелем или кабелем на базе витой пары.

Стример – ленточное устройство (dat drive) самый дешевый и надежный, но уже устаревший способ сохранения больших объемов информации. Запись производится на DAT-кассету. Скорость записи и чтения информации с кассеты лежит в пределах от 2 до 4 МБ в минуту.

Внешний жесткий диск (External hard drive) - распространенное, сравнительно быстрое устройство хранения информации. Может быть использован как для переноса информации на другие компьютеры, так и просто для расширения дискового пространства (чаще всего его используют именно для этого). Для хранения архивов использование внешнего винчестера хоть и удобно, но довольно дорого, как правило, емкость его измеряется гигабайтами, так как меньшие размеры просто невыгодны.

Сменный жесткий диск (Removable hard disk drive) – благодаря сравнительно небольшому времени доступа и простоте использования, это устройство получило довольно большое распространение. В основном используется для переноса больших объемов информации.

Разумеется, список устройств, которые могут быть подключены к ПК далеко не исчерпан. Тем более, что производители продолжают работать в этом направлении.

Файл

Информация в компьютере хранится на диске. Для того чтобы записать, а затем найти информацию на диске необходимо определить (назвать) место, где эта информация будет находится. Поименованное место на диске называется файлом. Размер файла измеряется в байтах и ограничивается только количеством свободного места »а диске.

Файлы бывают текстовые и двоичные.

Правила формирования имени файла Имя файла состоит из имени и расширения. Имя может содержать любое количество символов. Правда в «доисторической» операционной системе DOS, длинные имена файлов будут отсекаться до восьми символов. Недопустимо в именах файлов использовать специфические буквы типа І, і, Ї, ї, Є и є, а такие символы, как: : ? * [ ] { } < > / \ .,

Расширение отделяется от имени точкой и содержит до трех символов. Расширение характеризует тип файла. Например, расширения: .com .exe .bat соответствуют исполняемым файлам.

Исполняемый файл – это файл. в котором записана программа. Других расширений у исполняемых файлов пока нет.

Каталог или директория — это специальный файл, в который можно записывать другие файлы. На первых порах можно каталог отождествлять с разделом на диске. Правило формирования имени каталога такое же как и у файла, но каталог принято именовать без расширения. На каждом диске есть главный или начальный каталог, его еще называют корневым. Он создается операционной системой при подготовке диска к работе. Обозначают корневой каталог специальным символом, который называется слэш (\).

Каталог может включать в себя как файлы, так и другие каталоги, которые называются подкаталогами. Количество каталогов и их содержание определяется пользователем и ограничивается только наличием свободного места на диске.

Включение компьютера

Кнопка включения компьютера находится на корпусе. После включения компьютера проходит некоторое время, необходимое компьютеру на загрузку операционной системы. Нельзя включить и тут же выключить компьютер или выключить и немедленно включить компьютер. Между включением и выключением компьютера должно пройти не менее 10 секунд.

Если компьютер не реагирует ни на одну клавишу или необходимо просто начать сеанс работы сначала, то можно использовать клавишу Reset, которая находится на корпусе ПК. Эта клавиша создана именно для перезагрузки операционной системы. Сочетание клавиш. Ctrl+Alt+Delele также перезагружает операционную систему.

Очень вредно часто включать и выключать компьютер. Если необходимо оставить компьютер на небольшой интервал времени не выключайте его.

Компьютер работает под управлением операционной системы. Операционная система - это программа, которая загружается при включении компьютера. Она производит диалог с пользователем, осуществляет управление компьютером и его ресурсами (оперативной памятью, местом на диске), запускает другие программы на выполнение.

Операционная система обеспечивает пользователю и прикладным программам удобный способ общения (интерфейс) с устройствами компьютера. Как правило, персональный компьютер работает под управлением операционных систем Windows 98, Windows Millennium, Windows 2000, Windows XP фирмы Microsoft Corporation.

Windows – это не одна программа, а система программ. Диалог пользователя с операционной системой осуществляется с помощью системы меню, в которой собраны команды Windows и прикладные программы. Каждая команда в системе меню означает, что операционная система должна выполнить определенное действие. Команды Windows могут набираться пользователем с клавиатуры в специальном окне. Как правило, пользователем набираются с клавиатуры только те команды, Windows, которые имеют определенные параметры. В этом случае пользователь должен знать правила записи команд и синтаксис их написания. Вместе с тем, применяя систему меню у пользователя есть возможность запускать команды операционной системе, абсолютно не зная синтаксиса их написания. Но еще более удобные средства запуска команд Windows и работы с файлами пользователь может получить за счет использования специальных программ, называемых файловыми менеджерами.

Существует множество файловых менеджеров. Наиболее популярные среди них это Norton Commander и FAR Manager. Программа Norton Commander явилась первой яркой представительницей программных оболочек или файловых менеджеров. Благодаря чрезвычайно удобному интерфейсу, эта программа приобрела всемирную известность. Но, несмотря на то, что данная программа ежегодно обновляется, она с каждым годом теряет свою популярность. Слишком уж современный Norton Commander громоздок и сложен в освоении для пользователей. На смену данной программе по популярности пришел FAR Manager.

Заключение

Активное развитие микроэлектроники, появление и постоянное совершенствование микроминиатюрных интегральных электронных элементов создали основу для развития и совершенствования персональных компьютеров. Производительность их взросла на три порядка, при этом, что очень важно цена практически не изменилась. ПК стал доступен массовому потребителю, и теперь в развитых странах мира компьютер имеется на большинстве рабочих мест и в большинстве семей.

Сейчас ПК особенно популярны, т.к. они компактны, не требуют специальных условий эксплуатации, дешевы, благодаря дружественному интерфейсу с пользователем не требует специальной профессиональной подготовки при выполнении большей части работ. Все это обусловливается хорошо развитой и усовершенствованной архитектурой ПК, позволяющей активно, качественно, рационально и легко использовать ресурсы ЭВМ при информационно-вычислительных процессах. Так как в информационном обществе главным ресурсом является информация, именно на основе владения информацией о самых различных процессах и явлениях можно эффективно и оптимально строить любую деятельность. А эффективная работа компьютера обеспечивается взаимодействием всех его важнейших деталей и компонентов, образующих его архитектуру. Поэтому невозможно представить современные производственные процессы в мировом информационном сообществе без использования ПК с хорошо разработанной архитектурой.

Процесс усовершенствования ПК продолжается, разрабатываются и испытываются новейшие технологии в получении, обработке, хранении и передаче информации, изменяются и развиваются структурные элементы ПК, его работа становится все более производительной и качественной, а использование все более простым и понятным. Все это усиливает роль ПК как главного компонента при решении сложнейших задач и делает его незаменимым предметом в современной информационной эпохе.

Список литературы

  1. Жукова Е.Л., Бурда Е.Г. Информатика: Учебное пособие. – М.: Издательско-торговая корпорация «Дашков и К»; Ростов н/Д: Наука-Пресс, 2014. – 272 с.
  2. Информатика: Лабораторный практикум для студентов II курса всех специальностей. – М.: Вузовский учебник, 2015. – 94 с.
  3. Информатика: Методические указания по выполнению курсовой работы для самостоятельной работы студентов II курса (первое высшее образование). - М.: Вузовский учебник, 2015. – 60 с.
  4. Информатика: Учеб. пособие для студ. пед. Вузов / А.В. Могилев, Н.И. Пак, Е.К. Хеннер; Под ред. Е.К. Хеннера. – 2-е изд., стер. – М.: Изд. центр «Академия», 2016. – 816 с.
  5. Информатика: Учебник. – 3-е перераб. изд./Под ред. проф. Н.В. Макаровой. – М.: Финансы и статистика, 2016. – 768 с.
  6. Михеева Е.В. Информационные технологии в профессиональной деятельности: учеб. пособие для студ. сред. Проф. образования / Е.В. Михеева. – 6-е изд., стер. – М.: Издательский центр «Академия», 2014. – 384 с.
  7. Практическая информатика: Учебное пособие для средней школы. Универсальный курс. - М.: АСТ-ПРЕСС КНИГА, 2013.
  8. Угринович Н.Д. Информатика и информационные технологии. Учебник для 10-11 классов / Н.Д. Угринович. - М.: БИНОМ. Лаборатория знаний, 2013.
  9. Угринович Н.Д. Информатика: Базовый курс. Учебник для 7 класса / Н.Д. Угринович - М.: "БИНОМ. Лаборатория знаний", 2013.
  10. Устройства ввода. Устройства вывода. // ПК просто! Основы. - 2015. - №1, с.10-13.
  11. Шафрин Ю.А. Информационные технологии: В 2 ч. Ч.2: Офисная технология и информационные системы. - М.: Лаборатория Базовых Знаний, 2016.
  12. Хахутаишвили М.Ш. Информатика и информационные технологии в подготовке специалистов экономического профиля: Учебное пособие для средних специальных учебных заведений потребительской кооперации: Часть I / Под общ. науч. ред. д-ра пед. наук, проф. Н.Е. Астафьевой. – г. Мытищи Московск. обл.: ЦУМК Центросоюза Российской Феедрации, 2016. – 128 с.

Database error in antiplagiat.ru:

Invalid SQL: 1284

SELECT varname, value, datatype FROM setting;

MySQL Error : MySQL server has gone away

Error Number : 2006

Script : http://antiplagiat.ru

Referrer : http://www.antiplagiat.ru/Cabinet/Cabinet.aspx?folderId=33483538346

IP Address : 127.0.0.1

Username : an_User

Classname : vap_Database

MySQL Version :

Database Error: Unable to connect to the database:Could not connect to MySQL

Error 1018: Неправильный синтаксис около "%.*ls". Если имелась в виду часть табличной подсказки, то для этого теперь необходимо использовать ключевое слово A WITH и круглые скобки. Правильный синтаксис см. в электронной документации по SQL Server.

Database Error: Unable to connect to the database:Could not connect to database

SQL Server Error 1019: Недопустимый список столбцов после имени объекта в инструкции GRANT/REVOKE.

MySQL Error : Illegal mix of collations (cp1251_bin,IMPLICIT) and (latin1_bin,IMPLICIT) for operation '='

Error Number : 1267

Code errors:

Include php errors require('includes/application_top.php');

if (!tep_session_is_registered('customer_id')) { $navigation->set_snapshot();

tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));

require(DIR_WS_LANGUAGES. $language. '/'. FILENAME_ACCOUNT);

$breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_ACCOUNT, '', 'SSL'));?><html <?php echo HTML_PARAMS; ?>><head> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>"><title><?php echo TITLE; ?></title> <base href="<?php echo (($request_type == 'SSL') ? HTTPS_SERVER: HTTP_SERVER). DIR_WS_CATALOG; ?>">

<link rel="stylesheet" type="text/css" href="stylesheet.css"> <script language="javascript"><!function rowOverEffect(object) { if (object.className == 'moduleRow') object.className = 'moduleRowOver';

} function rowOutEffect(object) { if (object.className == 'moduleRowOver') object.className = 'moduleRow';//--></script> </head> <body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0"> <!-- header //--> <?php require(DIR_WS_INCLUDES. 'header.php'); ?>

<!-- header_eof //--> <!-- body //--> <table border="0" width="100%" cellspacing="3" cellpadding="3"> <tr> <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="0" cellpadding="2"> <!-- left_navigation //--> <?php require(DIR_WS_INCLUDES. 'column_left.php'); ?>

<!-- left_navigation_eof //--> </table></td> <!-- body_text //--> <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td class="pageHeading"><?php echo HEADING_TITLE; ?></td> <td class="pageHeading" align="right"><?php echo tep_image(DIR_WS_IMAGES. 'table_background_account.gif', HEADING_TITLE, HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td> </tr> </table></td> </tr> <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td> <?php if ($messageStack->size('account') > 0) { <td><?php echo $messageStack->output('account'); ?></td> if (tep_count_customer_orders() > 0) { <td><table border="0" cellspacing="0" cellpadding="2"> <td class="main"><b><?php echo OVERVIEW_TITLE; ?></b></td> <td class="main"><?php echo '<a href="'. tep_href_link(FILENAME_ACCOUNT_HISTORY, '', 'SSL'). '"><u>'. OVERVIEW_SHOW_ALL_ORDERS. '</u></a>'; ?></td> <td><table border="0" width="100%" cellspacing="1" cellpadding="2" class="infoBox"> <tr class="infoBoxContents"> <td><table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="main" align="center" valign="top" width="130"><?php echo '<b>'. OVERVIEW_PREVIOUS_ORDERS. '</b><br>'. tep_image(DIR_WS_IMAGES. 'arrow_south_east.gif'); ?></td> <td><table border="0" width="100%" cellspacing="0" cellpadding="2"> $orders_query = tep_db_query("select o.orders_id, o.date_purchased, o.delivery_name, o.delivery_country, o.billing_name, o.billing_country, ot.text as order_total, s.orders_status_name from ". TABLE_ORDERS. " o, ". TABLE_ORDERS_TOTAL. " ot, ". TABLE_ORDERS_STATUS. " s where o.customers_id = '". (int)$customer_id. "' and o.orders_id = ot.orders_id and ot.class = 'ot_total' and o.orders_status = s.orders_status_id and s.language_id = '". (int)$languages_id. "' and s.public_flag = '1' order by orders_id desc limit 3");

while ($orders = tep_db_fetch_array($orders_query)) { if (tep_not_null($orders['delivery_name'])) { $order_name = $orders['delivery_name'];

$order_country = $orders['delivery_country'];

} else { $order_name = $orders['billing_name'];

$order_country = $orders['billing_country'];

<tr class="moduleRow" onMouseOver="rowOverEffect(this)" onMouseOut="rowOutEffect(this)" onClick="document.location.href='<?php echo tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id='. $orders['orders_id'], 'SSL'); ?>'">

<td class="main" width="80"><?php echo tep_date_short($orders['date_purchased']); ?></td> <td class="main"><?php echo '#'. $orders['orders_id']; ?></td> <td class="main"><?php echo tep_output_string_protected($order_name). ', '. $order_country; ?></td> <td class="main"><?php echo $orders['orders_status_name']; ?></td> <td class="main" align="right"><?php echo $orders['order_total']; ?></td> <td class="main" align="right"><?php echo '<a href="'. tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id='. $orders['orders_id'], 'SSL'). '">'. tep_image_button('small_view.gif', SMALL_IMAGE_BUTTON_VIEW). '</a>'; ?></td> </tr> </table></td> <td><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td> </tr> </table></td> <td><table border="0" width="100%" cellspacing="0" cellpadding="2"> <td class="main"><b><?php echo MY_ACCOUNT_TITLE; ?></b></td> <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td> <td width="60"><?php echo tep_image(DIR_WS_IMAGES. 'account_personal.gif'); ?></td> <tr> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_EDIT, '', 'SSL'). '">'. MY_ACCOUNT_INFORMATION. '</a>'; ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ADDRESS_BOOK, '', 'SSL'). '">'. MY_ACCOUNT_ADDRESS_BOOK. '</a>'; ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_PASSWORD, '', 'SSL'). '">'. MY_ACCOUNT_PASSWORD. '</a>'; ?></td> <td width="10" align="right"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td> <td class="main"><b><?php echo MY_ORDERS_TITLE; ?></b></td> <td width="60"><?php echo tep_image(DIR_WS_IMAGES. 'account_orders.gif'); ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_HISTORY, '', 'SSL'). '">'. MY_ORDERS_VIEW. '</a>'; ?></td> <td class="main"><b><?php echo EMAIL_NOTIFICATIONS_TITLE; ?></b></td> <td width="60"><?php echo tep_image(DIR_WS_IMAGES. 'account_notifications.gif'); ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_NEWSLETTERS, '', 'SSL'). '">'. EMAIL_NOTIFICATIONS_NEWSLETTERS. '</a>'; ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_NOTIFICATIONS, '', 'SSL'). '">'. EMAIL_NOTIFICATIONS_PRODUCTS. '</a>'; ?></td> <!-- body_text_eof //--> <!-- right_navigation //--> <?php require(DIR_WS_INCLUDES. 'column_right.php'); ?><!-- right_navigation_eof //--> </tr> </table> <!-- body_eof //--> <!-- footer //--> <?php require(DIR_WS_INCLUDES. 'footer.php'); ?>

$type = (isset($HTTP_GET_VARS['type']) ? $HTTP_GET_VARS['type']: '');

$banner_extension = tep_banner_image_extension();// check if the graphs directory exists $dir_ok = false;if (function_exists('imagecreate') && tep_not_null($banner_extension)) { if (is_dir(DIR_WS_IMAGES. 'graphs')) { if (is_writeable(DIR_WS_IMAGES. 'graphs')) { $dir_ok = true;

$messageStack->add(ERROR_GRAPHS_DIRECTORY_NOT_WRITEABLE, 'error');

} else { $messageStack->add(ERROR_GRAPHS_DIRECTORY_DOES_NOT_EXIST, 'error');

$banner_query = tep_db_query("select banners_title from ". TABLE_BANNERS. " where banners_id = '". (int)$HTTP_GET_VARS['bID']. "'");

$banner = tep_db_fetch_array($banner_query);$years_array = array();

$years_query = tep_db_query("select distinct year(banners_history_date) as banner_year from ". TABLE_BANNERS_HISTORY. " where banners_id = '". (int)$HTTP_GET_VARS['bID']. "'");

while ($years = tep_db_fetch_array($years_query)) { $years_array[] = array('id' => $years['banner_year'], 'text' => $years['banner_year']);

$months_array = array();for ($i=1; $i<13; $i++) { $months_array[] = array('id' => $i, 'text' => strftime('%B', mktime(0,0,0,$i)));

$type_array = array(array('id' => 'daily', 'text' => STATISTICS_TYPE_DAILY), array('id' => 'monthly', 'text' => STATISTICS_TYPE_MONTHLY), array('id' => 'yearly', 'text' => STATISTICS_TYPE_YEARLY));

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <link rel="stylesheet" type="text/css" href="includes/stylesheet.css"> <body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF"> <table border="0" width="100%" cellspacing="2" cellpadding="2"> <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft"> <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr><?php echo tep_draw_form('year', FILENAME_BANNER_STATISTICS, '', 'get'); ?>

<td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', '1', HEADING_IMAGE_HEIGHT); ?></td> <td class="main" align="right"><?php echo TITLE_TYPE. ' '. tep_draw_pull_down_menu('type', $type_array, (tep_not_null($type) ? $type: 'daily'), 'onChange="this.form.submit();"'); ?><noscript><input type="submit" value="GO"></noscript><br> switch ($type) { case 'yearly': break;case 'monthly':

echo TITLE_YEAR. ' '. tep_draw_pull_down_menu('year', $years_array, (isset($HTTP_GET_VARS['year']) ? $HTTP_GET_VARS['year']: date('Y')), 'onChange="this.form.submit();"'). '<noscript><input type="submit" value="GO"></noscript>';

break;default:case 'daily':echo TITLE_MONTH. ' '. tep_draw_pull_down_menu('month', $months_array, (isset($HTTP_GET_VARS['month']) ? $HTTP_GET_VARS['month']: date('n')), 'onChange="this.form.submit();"'). '<noscript><input type="submit" value="GO"></noscript><br>'. TITLE_YEAR. ' '. tep_draw_pull_down_menu('year', $years_array, (isset($HTTP_GET_VARS['year']) ? $HTTP_GET_VARS['year']: date('Y')), 'onChange="this.form.submit();"'). '<noscript><input type="submit" value="GO"></noscript>';

</td> <?php echo tep_draw_hidden_field('page', $HTTP_GET_VARS['page']). tep_draw_hidden_field('bID', $HTTP_GET_VARS['bID']). tep_hide_session_id(); ?></form></tr> <td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td> <td align="center"> if (function_exists('imagecreate') && ($dir_ok == true) && tep_not_null($banner_extension)) { $banner_id = (int)$HTTP_GET_VARS['bID'];

switch ($type) { case 'yearly':

include(DIR_WS_INCLUDES. 'graphs/banner_yearly.php');

echo tep_image(DIR_WS_IMAGES. 'graphs/banner_yearly-'. $banner_id. '.'. $banner_extension);

break;

case 'monthly':include(DIR_WS_INCLUDES. 'graphs/banner_monthly.php');

echo tep_image(DIR_WS_IMAGES. 'graphs/banner_monthly-'. $banner_id. '.'. $banner_extension);

default:case 'daily':include(DIR_WS_INCLUDES. 'graphs/banner_daily.php');

echo tep_image(DIR_WS_IMAGES. 'graphs/banner_daily-'. $banner_id. '.'. $banner_extension);

<table border="0" width="600" cellspacing="0" cellpadding="2"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_SOURCE; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_VIEWS; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_CLICKS; ?></td> </tr> for ($i=0, $n=sizeof($stats); $i<$n; $i++) { echo ' <tr class="dataTableRow">'. "\n".

' <td class="dataTableContent">'. $stats[$i][0]. '</td>'. "\n".

' <td class="dataTableContent" align="right">'. number_format($stats[$i][1]). '</td>'. "\n".

' <td class="dataTableContent" align="right">'. number_format($stats[$i][2]). '</td>'. "\n".

' </tr>'. "\n";</table> } else { include(DIR_WS_FUNCTIONS. 'html_graphs.php');

echo tep_banner_graph_yearly($HTTP_GET_VARS['bID']);echo tep_banner_graph_monthly($HTTP_GET_VARS['bID']);echo tep_banner_graph_daily($HTTP_GET_VARS['bID']);

</td> <td class="main" align="right"><?php echo '<a href="'. tep_href_link(FILENAME_BANNER_MANAGER, 'page='. $HTTP_GET_VARS['page']. '&bID='. $HTTP_GET_VARS['bID']). '">'. tep_image_button('button_back.gif', IMAGE_BACK). '</a>'; ?></td> $action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action']: '');

if (tep_not_null($action)) { switch ($action) { case 'save':$configuration_value = tep_db_prepare_input($HTTP_POST_VARS['configuration_value']);

$cID = tep_db_prepare_input($HTTP_GET_VARS['cID']);

tep_db_query("update ". TABLE_CONFIGURATION. " set configuration_value = '". tep_db_input($configuration_value). "', last_modified = now() where configuration_id = '". (int)$cID. "'");

tep_redirect(tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cID));

$gID = (isset($HTTP_GET_VARS['gID'])) ? $HTTP_GET_VARS['gID']: 1;

$cfg_group_query = tep_db_query("select configuration_group_title from ". TABLE_CONFIGURATION_GROUP. " where configuration_group_id = '". (int)$gID. "'");

$cfg_group = tep_db_fetch_array($cfg_group_query);

<script language="javascript" src="includes/general.js"></script> <body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onload="SetFocus();">

<td class="pageHeading"><?php echo $cfg_group['configuration_group_title']; ?></td> <td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td> <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_CONFIGURATION_TITLE; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_CONFIGURATION_VALUE; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?>&nbsp;</td> $configuration_query = tep_db_query("select configuration_id, configuration_title, configuration_value, use_function from ". TABLE_CONFIGURATION. " where configuration_group_id = '". (int)$gID. "' order by sort_order");

while ($configuration = tep_db_fetch_array($configuration_query)) { if (tep_not_null($configuration['use_function'])) { $use_function = $configuration['use_function'];

if (ereg('->', $use_function)) { $class_method = explode('->', $use_function);

if (!is_object(${$class_method[0]})) { include(DIR_WS_CLASSES. $class_method[0]. '.php');

${$class_method[0]} = new $class_method[0]();

$cfgValue = tep_call_function($class_method[1], $configuration['configuration_value'], ${$class_method[0]});

$cfgValue = tep_call_function($use_function, $configuration['configuration_value']);

$cfgValue = $configuration['configuration_value'];

if ((!isset($HTTP_GET_VARS['cID']) || (isset($HTTP_GET_VARS['cID']) && ($HTTP_GET_VARS['cID'] == $configuration['configuration_id']))) && !isset($cInfo) && (substr($action, 0, 3) != 'new')) { $cfg_extra_query = tep_db_query("select configuration_key, configuration_description, date_added, last_modified, use_function, set_function from ". TABLE_CONFIGURATION. " where configuration_id = '". (int)$configuration['configuration_id']. "'");

$cfg_extra = tep_db_fetch_array($cfg_extra_query);$cInfo_array = array_merge($configuration, $cfg_extra);$cInfo = new objectInfo($cInfo_array);

if ( (isset($cInfo) && is_object($cInfo)) && ($configuration['configuration_id'] == $cInfo->configuration_id) ) { echo ' <tr id="defaultSelected" class="dataTableRowSelected" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id. '&action=edit'). '\'">'. "\n";

echo ' <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $configuration['configuration_id']). '\'">'. "\n";

<td class="dataTableContent"><?php echo $configuration['configuration_title']; ?></td> <td class="dataTableContent"><?php echo htmlspecialchars($cfgValue); ?></td> <td class="dataTableContent" align="right"><?php if ( (isset($cInfo) && is_object($cInfo)) && ($configuration['configuration_id'] == $cInfo->configuration_id) ) { echo tep_image(DIR_WS_IMAGES. 'icon_arrow_right.gif', ''); } else { echo '<a href="'. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $configuration['configuration_id']). '">'. tep_image(DIR_WS_IMAGES. 'icon_info.gif', IMAGE_ICON_INFO). '</a>'; } ?>&nbsp;</td> $heading = array();

$contents = array();switch ($action) { case 'edit':$heading[] = array('text' => '<b>'. $cInfo->configuration_title. '</b>');

if ($cInfo->set_function) { eval('$value_field = '. $cInfo->set_function. '"'. htmlspecialchars($cInfo->configuration_value). '");');

$value_field = tep_draw_input_field('configuration_value', $cInfo->configuration_value);

$contents = array('form' => tep_draw_form('configuration', FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id. '&action=save'));

$contents[] = array('text' => TEXT_INFO_EDIT_INTRO);$contents[] = array('text' => '<br><b>'. $cInfo->configuration_title. '</b><br>'. $cInfo->configuration_description. '<br>'. $value_field);

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_update.gif', IMAGE_UPDATE). '&nbsp;<a href="'. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');if (isset($cInfo) && is_object($cInfo)) { $heading[] = array('text' => '<b>'. $cInfo->configuration_title. '</b>');$contents[] = array('align' => 'center', 'text' => '<a href="'. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id. '&action=edit'). '">'. tep_image_button('button_edit.gif', IMAGE_EDIT). '</a>');

$contents[] = array('text' => '<br>'. $cInfo->configuration_description);

$contents[] = array('text' => '<br>'. TEXT_INFO_DATE_ADDED. ' '. tep_date_short($cInfo->date_added));

if (tep_not_null($cInfo->last_modified)) $contents[] = array('text' => TEXT_INFO_LAST_MODIFIED. ' '. tep_date_short($cInfo->last_modified));

case 'insert':$tax_zone_id = tep_db_prepare_input($HTTP_POST_VARS['tax_zone_id']);

$tax_class_id = tep_db_prepare_input($HTTP_POST_VARS['tax_class_id']);

$tax_rate = tep_db_prepare_input($HTTP_POST_VARS['tax_rate']);

$tax_description = tep_db_prepare_input($HTTP_POST_VARS['tax_description']);

$tax_priority = tep_db_prepare_input($HTTP_POST_VARS['tax_priority']);

tep_db_query("insert into ". TABLE_TAX_RATES. " (tax_zone_id, tax_class_id, tax_rate, tax_description, tax_priority, date_added) values ('". (int)$tax_zone_id. "', '". (int)$tax_class_id. "', '". tep_db_input($tax_rate). "', '". tep_db_input($tax_description). "', '". tep_db_input($tax_priority). "', now())");tep_redirect(tep_href_link(FILENAME_TAX_RATES));

$tax_rates_id = tep_db_prepare_input($HTTP_GET_VARS['tID']);

tep_db_query("update ". TABLE_TAX_RATES. " set tax_rates_id = '". (int)$tax_rates_id. "', tax_zone_id = '". (int)$tax_zone_id. "', tax_class_id = '". (int)$tax_class_id. "', tax_rate = '". tep_db_input($tax_rate). "', tax_description = '". tep_db_input($tax_description). "', tax_priority = '". tep_db_input($tax_priority). "', last_modified = now() where tax_rates_id = '". (int)$tax_rates_id. "'");

tep_redirect(tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $tax_rates_id));case 'deleteconfirm':tep_db_query("delete from ". TABLE_TAX_RATES. " where tax_rates_id = '". (int)$tax_rates_id. "'");

tep_redirect(tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']));

<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_TAX_RATE_PRIORITY; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_TAX_CLASS_TITLE; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_ZONE; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_TAX_RATE; ?></td> $rates_query_raw = "select r.tax_rates_id, z.geo_zone_id, z.geo_zone_name, tc.tax_class_title, tc.tax_class_id, r.tax_priority, r.tax_rate, r.tax_description, r.date_added, r.last_modified from ". TABLE_TAX_CLASS. " tc, ". TABLE_TAX_RATES. " r left join ". TABLE_GEO_ZONES. " z on r.tax_zone_id = z.geo_zone_id where r.tax_class_id = tc.tax_class_id";

$rates_split = new splitPageResults($HTTP_GET_VARS['page'], MAX_DISPLAY_SEARCH_RESULTS, $rates_query_raw, $rates_query_numrows);$rates_query = tep_db_query($rates_query_raw);

while ($rates = tep_db_fetch_array($rates_query)) { if ((!isset($HTTP_GET_VARS['tID']) || (isset($HTTP_GET_VARS['tID']) && ($HTTP_GET_VARS['tID'] == $rates['tax_rates_id']))) && !isset($trInfo) && (substr($action, 0, 3) != 'new')) { $trInfo = new objectInfo($rates);

if (isset($trInfo) && is_object($trInfo) && ($rates['tax_rates_id'] == $trInfo->tax_rates_id)) { echo ' <tr id="defaultSelected" class="dataTableRowSelected" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=edit'). '\'">'. "\n";

echo ' <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $rates['tax_rates_id']). '\'">'. "\n";

<td class="dataTableContent"><?php echo $rates['tax_priority']; ?></td> <td class="dataTableContent"><?php echo $rates['tax_class_title']; ?></td> <td class="dataTableContent"><?php echo $rates['geo_zone_name']; ?></td> <td class="dataTableContent"><?php echo tep_display_tax_value($rates['tax_rate']); ?>%</td> <td class="dataTableContent" align="right"><?php if (isset($trInfo) && is_object($trInfo) && ($rates['tax_rates_id'] == $trInfo->tax_rates_id)) { echo tep_image(DIR_WS_IMAGES. 'icon_arrow_right.gif', ''); } else { echo '<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $rates['tax_rates_id']). '">'. tep_image(DIR_WS_IMAGES. 'icon_info.gif', IMAGE_ICON_INFO). '</a>'; } ?>&nbsp;</td> <td colspan="5"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <td class="smallText" valign="top"><?php echo $rates_split->display_count($rates_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $HTTP_GET_VARS['page'], TEXT_DISPLAY_NUMBER_OF_TAX_RATES); ?></td> <td class="smallText" align="right"><?php echo $rates_split->display_links($rates_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $HTTP_GET_VARS['page']); ?></td> if (empty($action)) { <td colspan="5" align="right"><?php echo '<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&action=new'). '">'. tep_image_button('button_new_tax_rate.gif', IMAGE_NEW_TAX_RATE). '</a>'; ?></td> case 'new':

$heading[] = array('text' => '<b>'. TEXT_INFO_HEADING_NEW_TAX_RATE. '</b>');

$contents = array('form' => tep_draw_form('rates', FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&action=insert'));$contents[] = array('text' => TEXT_INFO_INSERT_INTRO);

$contents[] = array('text' => '<br>'. TEXT_INFO_CLASS_TITLE. '<br>'. tep_tax_classes_pull_down('name="tax_class_id" style="font-size:10px"'));

$contents[] = array('text' => '<br>'. TEXT_INFO_ZONE_NAME. '<br>'. ep_geo_zones_pull_down('name="tax_zone_id" style="font-size:10px"'));$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE. '<br>'. tep_draw_input_field('tax_rate'));

$contents[] = array('text' => '<br>'. TEXT_INFO_RATE_DESCRIPTION. '<br>'. tep_draw_input_field('tax_description'));$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE_PRIORITY. '<br>'. tep_draw_input_field('tax_priority'));

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_insert.gif', IMAGE_INSERT). '&nbsp;<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');

$heading[] = array('text' => '<b>'. TEXT_INFO_HEADING_EDIT_TAX_RATE. '</b>');

$contents = array('form' => tep_draw_form('rates', FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=save'));

$contents[] = array('text' => '<br>'. TEXT_INFO_CLASS_TITLE. '<br>'. tep_tax_classes_pull_down('name="tax_class_id" style="font-size:10px"', $trInfo->tax_class_id));

$contents[] = array('text' => '<br>'. TEXT_INFO_ZONE_NAME. '<br>'. tep_geo_zones_pull_down('name="tax_zone_id" style="font-size:10px"', $trInfo->geo_zone_id));

$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE. '<br>'. tep_draw_input_field('tax_rate', $trInfo->tax_rate));$contents[] = array('text' => '<br>'. TEXT_INFO_RATE_DESCRIPTION. '<br>'. tep_draw_input_field('tax_description', $trInfo->tax_description));

$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE_PRIORITY. '<br>'. tep_draw_input_field('tax_priority', $trInfo->tax_priority));

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_update.gif', IMAGE_UPDATE). '&nbsp;<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');case 'delete':

$heading[] = array('text' => '<b>'. TEXT_INFO_HEADING_DELETE_TAX_RATE. '</b>');

$contents = array('form' => tep_draw_form('rates', FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=deleteconfirm'));

$contents[] = array('text' => TEXT_INFO_DELETE_INTRO);$contents[] = array('text' => '<br><b>'. $trInfo->tax_class_title. ' '. number_format($trInfo->tax_rate, TAX_DECIMAL_PLACES). '%</b>');

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_delete.gif', IMAGE_DELETE). '&nbsp;<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');

if (is_object($trInfo)) { $heading[] = array('text' => '<b>'. $trInfo->tax_class_title. '</b>');

$contents[] = array('align' => 'center', 'text' => '<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=edit'). '">'. tep_image_button('button_edit.gif', IMAGE_EDIT). '</a> <a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=delete'). '">'. tep_image_button('button_delete.gif', IMAGE_DELETE). '</a>');

$contents[] = array('text' => '<br>'. TEXT_INFO_DATE_ADDED. ' '. tep_date_short($trInfo->date_added));

$contents[] = array('text' => ''. TEXT_INFO_LAST_MODIFIED. ' '. tep_date_short($trInfo->last_modified));

$contents[] = array('text' => '<br>'. TEXT_INFO_RATE_DESCRIPTION. '<br>'. $trInfo->tax_description);

define('OSC_CATALOG_SESSION_ID', 'osCsid');function tep_create_random_value($length, $type = 'mixed') { if ( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) return false;

$rand_value = '';while (strlen($rand_value) < $length) { if ($type == 'digits') { $char = tep_rand(0,9);

$char = chr(tep_rand(0,255));if ($type == 'mixed') { if (eregi('^[a-z0-9]$', $char)) $rand_value.= $char;

} elseif ($type == 'chars') { if (eregi('^[a-z]$', $char)) $rand_value.= $char;

} elseif ($type == 'digits') { if (ereg('^[0-9]$', $char)) $rand_value.= $char;

return $rand_value;// Module already installed if (defined('MODULE_PAYMENT_SOFORTUEBERWEISUNG_DIRECT_STATUS') && (MODULE_PAYMENT_SOFORTUEBERWEISUNG_DIRECT_STATUS == 'True')) { die('Modul bereits installiert<br><a href="'. tep_href_link(FILENAME_MODULES, 'set=payment&module=sofortueberweisung_direct', 'SSL'). '">zurьck zum ShopAdmin</a>');

$parameter = array();$parameter['install'] = 'sofortueberweisung_direct';

$parameter['action'] = 'install';$parameter['input_passwort'] = tep_create_random_value(12);

$parameter['bna_passwort'] = tep_create_random_value(12);$parameter['cnt_passwort'] = tep_create_random_value(12);$get_parameter = '';$x = 0;while(list($key,$value) = each($parameter)) { if (empty($value)) continue;

if ($x > 0) $get_parameter.= "&";$get_parameter.= $key. "=". urlencode($value);

$x++;$backlink = tep_href_link('ext/modules/payment/sofortueberweisung/install.php', $get_parameter);$html_abortlink = tep_catalog_href_link('checkout_payment.php', 'payment_error=sofortueberweisung_direct&'. OSC_CATALOG_SESSION_ID. '=-KUNDEN_VAR_2-','SSL', false, false);$header_redir_url = tep_catalog_href_link('checkout_process.php', OSC_CATALOG_SESSION_ID. '=-KUNDEN_VAR_2-&sovar3=-KUNDEN_VAR_3-&sovar4=-KUNDEN_VAR_3_MD5_PASS-&betrag_integer=-BETRAG_INTEGER-','SSL', false, false);

$alert_http_url = ep_catalog_href_link('ext/modules/payment/sofortueberweisung/callback.php','','SSL', false, false);

if (isset($HTTP_GET_VARS['action']) && ($HTTP_GET_VARS['action'] == 'install')) { $file_extension = substr($PHP_SELF, strrpos($PHP_SELF, '.'));$class = 'sofortueberweisung_direct';

if (file_exists(DIR_FS_CATALOG_MODULES. 'payment/sofortueberweisung_direct'. $file_extension)) { include(DIR_FS_CATALOG_MODULES. 'payment/sofortueberweisung_direct'. $file_extension);

$module = new $class;$module->install();tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=sofortueberweisung_direct', 'SSL'));<html> <link rel="stylesheet" type="text/css" href="https://www.sofortueberweisung.de/cms/modul/style.css"> <script type="text/javascript"> function init() { if(false) { document.getElementById('table1').style.display = '';

document.getElementById('table2').style.display = ''; document.getElementById('table3').style.display = ''; document.getElementById('table4').style.display = '';ocument.getElementById('table5').style.display = ''; document.getElementById('table6').style.display = '';function toggleTableById(id) { if(document.getElementById(id).style.display == 'none') document.getElementById(id).style.display = ''; else document.getElementById(id).style.display = 'none';function giveValue(value,name0, name1, name2, name3, name4) { if(name0 != '') document.getElementsByName(name0)[0].value = value;

if(name1 != '') document.getElementsByName(name1)[0].value = value; if(name2 != '') document.getElementsByName(name2)[0].value = value; if(name3 != '') ocument.getElementsByName(name3)[0].value = value; if(name4 != '') document.getElementsByName(name4)[0].value = value;function checkChar(string, validChars) { for (var pos = 0; pos < string.length; pos++) { if (validChars.indexOf(string.charAt(pos)) == -1) { return false;

return true;function submitForm() { var is_error=false;

var wert, wert1, wert2; wert = document.getElementById('sammel_input_project_name').value;

if(!is_error) if(wert == '') {alert('Bitte Projektnamen eintragen'); is_error=true;} wert = document.getElementById('sammel_input_name').value;

if(!is_error) if(wert == '') {alert('Bitte Namen eintragen'); is_error=true;} wert = document.getElementById('sammel_input_firma').value;

if(!is_error) if(wert == '') {alert('Bitte Firma eintragen'); is_error=true;} wert = document.getElementById('sammel_input_strasse').value;

if(!is_error) if(wert == '') {alert('Bitte Strasse eintragen'); is_error=true;} wert = document.getElementById('sammel_input_plz').value;

if(!is_error) if(!checkChar(wert,'0123456789') || wert == '' || (wert.length!=5 && wert.length!=4)) {alert('PLZ muss aus 4 oder 5 Ziffern bestehen'); is_error=true;} wert = document.getElementById('sammel_input_ort').value;

if(!is_error) if(wert == '') {alert('Bitte Ort eintragen'); is_error=true;} wert = document.getElementById('sammel_input_land').value;

if(!is_error) if(wert == '') {alert('Bitte Land eintragen'); is_error=true;} wert = document.getElementById('sammel_input_konto_inhaber').value;

if(!is_error) if(wert == '') {alert('Bitte Kontoinhaber eintragen'); is_error=true;} wert = document.getElementById('sammel_input_kontonummer').value;

if(!is_error) if(!checkChar(wert,'0123456789') || wert == '') {alert('Kontonummer darf nur aus Ziffern bestehen'); is_error=true;} wert = document.getElementById('sammel_input_blz').value;

if(!is_error) if(!checkChar(wert,'0123456789') || wert == '' || wert.length!=8) {alert('BLZ muss aus 8 Ziffern bestehen'); is_error=true;} wert = document.getElementById('sammel_input_bank').value;

if(!is_error) if(wert == '') {alert('Bitte Bankname eintragen'); is_error=true;} wert = document.getElementById('sammel_input_homepage').value;

if(!is_error) if(wert == '') {alert('Bitte Homepage eintragen'); is_error=true;} wert = document.getElementById('sammel_input_email').value;

if(!is_error) if(wert == '') {alert('Bitte Email-Adresse eintragen'); is_error=true;} //if(!is_error) if(document.getElementById('sammel_input_ustid').value == '' && document.getElementById('sammel_input_steuernummer').value == '') {alert('Bitte alle Pflichtfelder ausfьllen'); is_error=true;} wert1 = document.getElementById('sammel_input_telefon').value;

wert2 = document.getElementById('sammel_input_mobil').value;

if(!is_error) if(wert1 == '' && wert2 == '') {alert('Es muss mindestens ein telefonischer Kontakt angegeben sein'); is_error=true;} // adjust Backlink document.getElementsByName('user[backlink]')[0].value += '&konto_inhaber=' + escape(document.getElementById('sammel_input_konto_inhaber').value);

document.getElementsByName('user[backlink]')[0].value += '&konto_nr=' + escape(document.getElementById('sammel_input_kontonummer').value);

document.getElementsByName('user[backlink]')[0].value += '&konto_blz=' + escape(document.getElementById('sammel_input_blz').value);

document.getElementsByName('user[backlink]')[0].value += '&konto_bank=' + escape(document.getElementById('sammel_input_bank').value);

if(!is_error) document.getElementById('form').submit();

</script> <style> input {Font-family:tahoma,arial,verdana; font-size:11px; color:#666666; background-color:#FFFFFF; border:1px solid #808080;} select {Font-family:tahoma,arial,verdana; font-size:11px; color:#666666; background-color:#FFFFFF; border:1px solid #808080;} </style> <body background="https://www.sofortueberweisung.de/cms/design/kachel.gif" leftmargin="0" topmargin="5" marginwidth="0" marginheight="0" onload="javascript:init()"> <form method="post" action="https://www.sofort-ueberweisung.de/createnew.php" id="form"> <table align="center" width="970" height="205" border="0" cellpadding="0" cellspacing="0"> <td> <img src="https://www.sofortueberweisung.de/grafik/head_image.gif" /> </td> <img src="https://www.sofortueberweisung.de/cms/p.gif" width=5 height=5 alt="" border=0 vspace=0 hspace=0> </td> <table align="center" width="970" border="0" cellpadding="0" cellspacing="0"> <tr> <td><img src="https://www.sofortueberweisung.de/cms/design/content_01.gif" width="190" height="10" alt="" border=0 vspace=0 hspace=0></td> <td><img src="https://www.sofortueberweisung.de/cms/design/content_02.gif" width="212" height="10" alt="" border=0 vspace=0 hspace=0></td> <td align="right"><img src="https://www.sofortueberweisung.de/cms/design/content_03.gif" width="568" height="10" alt="" border=0 vspace=0 hspace=0></td> </tr> </table> <td bgcolor="white"> <table width="100%" border="0"> <tr> <td width="50%"> <table border="0" cellpadding="2" cellspacing="0" style="padding-left: 20px;">

<tr><td>Projektname*</td><td><input id="sammel_input_project_name" size="40" type="text" value="<?php echo STORE_NAME; ?>" onkeyup="javascript:giveValue(this.value,'project[projekt_name]', '', '', '', '')"></td></tr> <tr><td>Projektbeschreibung</td><td><input size="40" type="text" onkeyup="javascript:giveValue(this.value,'project[projekt_beschreibung]', '', '', '', '' )"></td></tr> <tr><td colspan="2"><hr /></td></tr> <tr><td>Anrede</td><td><input size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[r_anrede]','user[anspr_anrede]','project[anrede]', '', '')"></td></tr> <tr><td>Name*</td><td><input id="sammel_input_name" value="<?php echo STORE_OWNER; ?>" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[r_name]','user[anspr_name]','project[name]', '', '')"> <tr><td>Firma*</td><td><input id="sammel_input_firma" size="40" type="text" value="<?php echo STORE_NAME; ?>" onkeyup="javascript:giveValue(this.value,'user[firma]','user[r_firma]','project[firma]', '', '')"></td></tr> <tr><td>Rechtsform</td><td> <select onchange="javascript:giveValue(this.value,'user[rechtsform]', '', '', '', '')"> <option value="">Bitte auswдhlen...</option> <option value="AG" >AG</option> <option value="AG & Co. OHG" >AG & Co. OHG</option> <option value="ARGE" >ARGE</option> <option value="e.G." >e.G.</option> <option value="e.K." >e.K.</option> <option value="e.V." >e.V.</option> <option value="GbR" >GbR</option> <option value="GmbH" >GmbH</option> <option value="GmbH & Co. KG" >GmbH & Co. KG</option> <option value="GmbH & Co. OHG" >GmbH & Co. OHG</option> <option value="KG" >KG</option> <option value="KGaA" >KGaA</option> <option value="OHG" >OHG</option> <option value="Selbststдndig" >Selbststдndig</option> <option value="VvAG" >VvAG</option> <option value="Sonstige" >Sonstige</option> </select> <tr><td>Strasse*</td><td><input id="sammel_input_strasse" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[strasse]','user[r_strasse]','project[strasse]', '', '')"></td></tr> <tr><td>PLZ*</td><td><input maxlength="5" id="sammel_input_plz" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[plz]','user[r_plz]','project[plz]', '', '')"></td></tr> <tr><td>Ort*</td><td><input id="sammel_input_ort" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[ort]','user[r_ort]','project[ort]', '', '')"></td></tr> <tr><td>Land*</td><td><input id="sammel_input_land" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[land]','user[r_land]','project[land]', '', '')"></td></tr> <tr><td>Telefon+</td><td><input id="sammel_input_telefon" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[telefon]','user[anspr_fon]','project[telefon]', '', '')"></td></tr> <tr><td>Mobil+</td><td><input id="sammel_input_mobil" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[anspr_mobil]', '', '', '', '')"></td></tr> <tr><td>Telefax</td><td><input size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[anspr_fax]','project[telefax]','user[telefax]', '', '')"></td></tr> <tr><td colspan="2"><hr /></td></tr> <tr><td colspan="2"><b>Konto auf welches die Zahlungseingдnge gutgeschrieben werden:</b></td></tr> <tr><td>Konto Inhaber*</td><td><input id="sammel_input_konto_inhaber" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_inhaber]', 'project[an_konto_inhaber]', '', '', '')"></td></tr> <tr><td>Kontonummer*</td><td><input maxlength="15" id="sammel_input_kontonummer" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_nr]', 'project[an_konto_nr]', '', '', '')"></td></tr> <tr><td>Bankleitzahl*</td><td><input maxlength="8" id="sammel_input_blz" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_blz]', 'project[an_konto_blz]', '', '', '')"></td></tr> <tr><td>Name der Bank*</td><td><input id="sammel_input_bank" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_bank]', 'project[an_konto_bank]', '', '', '')"></td></tr> <tr><td colspan="2"><b>Hiermit beauftrage ich Sie, die fдlligen <a href="https://www.sofortueberweisung.de/cms/index.php?plink=tarife&l=1&fs=" target="_blank">Betrдge</a> per Lastschrift von meinem Konto einzuziehen.</b></td></tr> <tr><td>Ustid</td><td><input id="sammel_input_ustid" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[ustid]', '', '', '', '')"></td></tr> <tr><td>Steuernr</td><td><input id="sammel_input_steuernummer" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[steuernr]', '', '', '', '')"></td></tr> <tr><td>Homepage*</td><td><input id="sammel_input_homepage" size="40" type="text" value="<?php echo tep_catalog_href_link();?>" onkeyup="javascript:giveValue(this.value,'project[homepage]','user[homepage]', '', '', '')"></td></tr> <tr><td>Email*</td><td><input id="sammel_input_email" size="40" type="text" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>" onkeyup="javascript:giveValue(this.value,'user[r_email]','user[anspr_email]','project[email]','user[email]','alert[alert_email_adresse]')"></td></tr> <tr><td>Email-Benachrichtigungen bei Zahlungseingдngen aktivieren:</td> <td><input type="radio" name="sammel_input_email_flag" value="1" CHECKED onfocus="javascript:giveValue(this.value,'alert[alert_email_status]', '', '', '', '')"> Ja <input type="radio" name="sammel_input_email_flag" value="0" onfocus="javascript:giveValue(this.value,'alert[alert_email_status]', '', '', '', '')"> Nein</td> </tr> <tr> <td colspan="2"> <input type="button" name="Absenden" value="Absenden" onclick="javascript:submitForm()"><br><b>Nach der Registrierung des Projekts bei Sofortьberweisung, unbedingt dem Link zurьck zum Shop folgen!</b> </td> </tr> </table> </td> <td valign="top" align="left"> <table border="0" cellspacing="0"> <tr><td><a href="#" onclick="javascript:toggleTableById('table2')"><u>Alternative Rechnungsanschrift</u></a></td></tr> <tr><td> <table border="0" cellspacing="0" id="table2" style="display:none"> <tr><td>Anrede</td><td><input size="40" type="text" name="user[r_anrede]" value=""></td></tr> <tr><td>Firma</td><td><input size="40" type="text" name="user[r_firma]" value="<?php echo STORE_NAME; ?>"></td></tr> <tr><td>Name</td><td><input size="40" type="text" name="user[r_name]" value=""></td></tr> <tr><td>Strasse</td><td><input size="40" type="text" name="user[r_strasse]" value=""></td></tr> <tr><td>Plz</td><td><input size="40" type="text" name="user[r_plz]" value=""></td></tr> <tr><td>Ort</td><td><input size="40" type="text" name="user[r_ort]" value=""></td></tr> <tr><td>Land</td><td><input size="40" type="text" name="user[r_land]" value=""></td></tr> <tr><td>Email</td><td><input size="40" type="text" name="user[r_email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td></tr> </table> </td></tr> <table border="0" cellspacing="0"> <tr><td><a href="#" onclick="javascript:toggleTableById('table4')"><u>Alternativer Ansprechpartner</u></a></td></tr> <tr><td> <table border="0" cellspacing="0" id="table4" style="display:none"> <tr><td>Anrede</td><td><input size="40" type="text" name="user[anspr_anrede]" value=""></td><td>&nbsp;</td></tr> <tr><td>Name</td><td><input size="40" type="text" name="user[anspr_name]" value=""></td><td>&nbsp;</td></tr> <tr><td>Telefon</td><td><input size="40" type="text" name="user[anspr_fon]" value=""></td><td>&nbsp;</td></tr> <tr><td>Telefax</td><td><input size="40" type="text" name="user[anspr_fax]" value=""></td><td>&nbsp;</td></tr> <tr><td>Mobil</td><td><input size="40" type="text" name="user[anspr_mobil]" value=""></td><td>&nbsp;</td></tr> <tr><td>Email</td><td><input size="40" type="text" name="user[anspr_email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>&nbsp;</td></tr> </table> </td></tr> </table> </tr> <tr><td style="padding-left: 20px;">* zeichnet Pflichtfelder aus<br />+ zeichnet Felder aus, bei denen mindestens eines gefьllt sein muss<br />Alle Zahlen sind ohne Leerzeichen einzugeben</td></tr> </table> </td></tr> <table width="970" border="0" cellspacing="0" cellpadding="0"> <td width="190" valign="top"><img src="https://www.sofortueberweisung.de/cms/design/content_11.gif" width=190 height=10 alt="" border=0 vspace=0 hspace=0></td> <td bgcolor="white"><img src="https://www.sofortueberweisung.de/cms/p.gif" width=5 height=10 alt="" border=0 vspace=0 hspace=0></td> <td align="right" width="568"><img src="https://www.sofortueberweisung.de/cms/design/content_13.gif" width=568 height=10 alt="" border=0 vspace=0 hspace=0></td> </tr> <table border="1" id="table1" style="display:none;">

<tr><td>Benutzername:</td><td><input type="text" name="user[user]" value="<?php echo STORE_OWNER; ?>"></td><td>*</td></tr> <tr><td>Firma</td><td><input type="text" name="user[firma]" value="<?php echo STORE_NAME; ?>"></td><td>*</td></tr> <tr><td>Rechtsform</td><td><input type="text" name="user[rechtsform]" value=""></td><td>&nbsp;</td></tr> <tr><td>Strasse</td><td><input type="text" name="user[strasse]" value=""></td><td>*</td></tr> <tr><td>Plz</td><td><input type="text" name="user[plz]" value=""></td><td>*</td></tr> <tr><td>Ort</td><td><input type="text" name="user[ort]" value=""></td><td>*</td></tr> <tr><td>Land</td><td><input type="text" name="user[land]" value=""></td><td>*</td></tr> </table> <table border="1" id="table3" style="display:none"> <tr><td>Telefon</td><td><input type="text" name="user[telefon]" value=""></td><td>&nbsp;</td></tr> <tr><td>Telefax</td><td><input type="text" name="user[telefax]" value=""></td><td>&nbsp;</td></tr> <tr><td>Email</td><td><input type="text" name="user[email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>*</td></tr> <tr><td>Homepage</td><td><input type="text" name="user[homepage]" value="<?php echo tep_catalog_href_link();?>"></td><td>&nbsp;</td></tr> <tr><td>Ustid</td><td><input type="text" name="user[ustid]" value=""></td><td>*</td></tr> <tr><td>Steuernr</td><td><input type="text" name="user[steuernr]" value=""></td><td>*</td></tr> <table border="1" id="table5" style="display:none;">

<tr><td colspan=3>Konto, von dem die Gebьhren von Sofort-Ьberweisung abgebucht werden:</td></tr> <tr><td>Konto Inhaber</td><td><input type="text" name="user[elv_konto_inhaber]" value=""></td><td>*</td></tr> <tr><td>Kontonr</td><td><input type="text" name="user[elv_konto_nr]" value=""></td><td>*</td></tr> <tr><td>Konto BLZ</td><td><input type="text" name="user[elv_konto_blz]" value=""></td><td>*</td></tr> <tr><td>Konto Bank</td><td><input type="text" name="user[elv_konto_bank]" value=""></td><td>*</td></tr> <table border="0" cellspacing="0" id="table6" style="display:none"> <tr><td>Name</td><td><input type="text" name="project[projekt_name]" value="<?php echo STORE_NAME; ?>"></td><td>*</td></tr> <tr><td>Beschreibung</td><td><input type="text" name="project[projekt_beschreibung]" value=""></td><td>&nbsp;</td></tr> <tr><td>Anrede</td><td><input type="text" name="project[anrede]" value=""></td><td>*</td></tr> <tr><td>Firma</td><td><input type="text" name="project[firma]" value="<?php echo STORE_NAME; ?>"></td><td>*</td></tr> <tr><td>Name</td><td><input type="text" name="project[name]" value="<?php echo STORE_OWNER; ?>"></td><td>*</td></tr> <tr><td>Strasse</td><td><input type="text" name="project[strasse]" value=""></td><td>*</td></tr> <tr><td>Plz</td><td><input type="text" name="project[plz]" value=""></td><td>*</td></tr> <tr><td>Ort</td><td><input type="text" name="project[ort]" value=""></td><td>*</td></tr> <tr><td>Land</td><td><input type="text" name="project[land]" value=""></td><td>*</td></tr> <tr><td>Telefon</td><td><input type="text" name="project[telefon]" value=""></td><td>*</td></tr> <tr><td>Telefax</td><td><input type="text" name="project[telefax]" value=""></td><td>*</td></tr> <tr><td>Email</td><td><input type="text" name="project[email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>*</td></tr> <tr><td>Homepage</td><td><input type="text" name="project[homepage]" value="<?php echo tep_catalog_href_link();?>"></td><td>*</td></tr> <table border="1" id="table7" style="display:none"> <tr><td>Email</td><td><input type="text" name="alert[alert_email_adresse]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>&nbsp;</td></tr> <tr><td>Email Benachrichtigung bei Zahlungseingang aktivieren</td><td><input type="text" name="alert[alert_email_status]" value="1"></td><td>&nbsp;</td></tr> <input type="hidden" name="user[backlink]" value="<?php echo $backlink; ?>">

<input type="hidden" name="user[vpartner]" value="21"> <input type="hidden" name="project[html_abortlink]" value="<?php echo $html_abortlink; ?>">

<input type="hidden" name="project[header_redir_do]" value="1"> <input type="hidden" name="project[header_redir_url]" value="<?php echo $header_redir_url; ?>">

<input type="hidden" name="project[const_betrag]" value="1"> <input type="hidden" name="project[const_v_zweck_1]" value="1"> <input type="hidden" name="project[const_v_zweck_2]" value="1"> <input type="hidden" name="project[use_input_passwort]" value="1"> <input type="hidden" name="project[an_konto_inhaber]" value=""> <input type="hidden" name="project[an_konto_nr]" value=""> <input type="hidden" name="project[an_konto_blz]" value=""> <input type="hidden" name="project[an_konto_bank]" value=""> <input type="hidden" name="project[input_passwort]" value="<?php echo $parameter['input_passwort']; ?>">

<input type="hidden" name="project[content_passwort]" value="<?php echo $parameter['cnt_passwort']; ?>">

<input type="hidden" name="project[shopsystem]" value="<?php echo PROJECT_VERSION; ?>">

<input type="hidden" name="alert[alert_passwort]" value="<?php echo $parameter['bna_passwort']; ?>">

<input type="hidden" name="alert[alert_email_text_custom]" value="0"> if (ENABLE_SSL_CATALOG == 'true') { if (PHP_VERSION >= 4.1) { $HTTP_GET_VARS =& $_GET;

$HTTP_POST_VARS =& $_POST;

$HTTP_COOKIE_VARS =& $_COOKIE;

$HTTP_SESSION_VARS =& $_SESSION;

$HTTP_POST_FILES =& $_FILES;

$HTTP_SERVER_VARS =& $_SERVER;

if (!is_array($HTTP_GET_VARS)) $HTTP_GET_VARS = array();

if (!is_array($HTTP_POST_VARS)) $HTTP_POST_VARS = array();

if (!is_array($HTTP_COOKIE_VARS)) $HTTP_COOKIE_VARS = array();

// handle magic_quotes_gpc turned off.

if (!get_magic_quotes_gpc()) { do_magic_quotes_gpc($HTTP_GET_VARS);

do_magic_quotes_gpc($HTTP_POST_VARS);

do_magic_quotes_gpc($HTTP_COOKIE_VARS);

if (!function_exists('is_numeric')) { function is_numeric($param) { return ereg("^[0-9]{1,50}.?[0-9]{0,50}$", $param);

if (!function_exists('is_uploaded_file')) { function is_uploaded_file($filename) { if (!$tmp_file = get_cfg_var('upload_tmp_dir')) { $tmp_file = dirname(tempnam('', ''));

if (strchr($tmp_file, '/')) { if (substr($tmp_file, -1) != '/') $tmp_file.= '/';

} elseif (strchr($tmp_file, '\\')) { if (substr($tmp_file, -1) != '\\') $tmp_file.= '\\';

return file_exists($tmp_file. basename($filename));

if (!function_exists('move_uploaded_file')) { function move_uploaded_file($file, $target) { return copy($file, $target);

if (!function_exists('checkdnsrr')) { function checkdnsrr($host, $type) { if(tep_not_null($host) && tep_not_null($type)) { @exec("nslookup -type=$type $host", $output);

while(list($k, $line) = each($output)) { if(eregi("^$host", $line)) { return true;

if (!function_exists('in_array')) { function in_array($lookup_value, $lookup_array) { reset($lookup_array);

while (list($key, $value) = each($lookup_array)) { if ($value == $lookup_value) return true;

if (!function_exists('array_merge')) { function array_merge($array1, $array2, $array3 = '') { if ($array3 == '') $array3 = array();

while (list($key, $val) = each($array1)) $array_merged[$key] = $val;

while (list($key, $val) = each($array2)) $array_merged[$key] = $val;

if (sizeof($array3) > 0) while (list($key, $val) = each($array3)) $array_merged[$key] = $val;

return (array)$array_merged;

if (!function_exists('array_shift')) { function array_shift(&$array) { $i = 0;

$shifted_array = array();

reset($array);

while (list($key, $value) = each($array)) { if ($i > 0) { $shifted_array[$key] = $value;

} else { $return = $array[$key];

$i++;

$array = $shifted_array;

return $return;

if (!function_exists('array_reverse')) { function array_reverse($array) { $reversed_array = array();

for ($i=sizeof($array)-1; $i>=0; $i--) { $reversed_array[] = $array[$i];

return $reversed_array;

if (!function_exists('array_slice')) { function array_slice($array, $offset, $length = '0') { $length = abs($length);

if ($length == 0) { $high = sizeof($array);

$high = $offset+$length;

for ($i=$offset; $i<$high; $i++) { $new_array[$i-$offset] = $array[$i];

return $new_array;* http_build_query() natively supported from PHP 5.0

* From Pear::PHP_Compat */ if ( !function_exists('http_build_query') && (PHP_VERSION >= 4)) { function http_build_query($formdata, $numeric_prefix = null, $arg_separator = null) { // If $formdata is an object, convert it to an array if ( is_object($formdata) ) { $formdata = get_object_vars($formdata);

// Check we have an array to work with if ( !is_array($formdata) || !empty($formdata) ) { return false;

// Argument seperator if ( empty($arg_separator) ) { $arg_separator = ini_get('arg_separator.output');

if ( empty($arg_separator) ) { $arg_separator = '&';

// Start building the query $tmp = array();

foreach ( $formdata as $key => $val ) { if ( is_null($val) ) { continue;

if ( is_integer($key) && ( $numeric_prefix != null ) ) { $key = $numeric_prefix. $key;

if ( is_scalar($val) ) { array_push($tmp, urlencode($key). '='. urlencode($val));

// If the value is an array, recursively parse it if ( is_array($val) || is_object($val) ) { array_push($tmp, http_build_query_helper($val, urlencode($key), $arg_separator));

// The value is a resource return null;

return implode($arg_separator, $tmp);

// Helper function function http_build_query_helper($array, $name, $arg_separator) { foreach ( $array as $key => $value ) { if ( is_array($value) ) { array_push($tmp, http_build_query_helper($value, sprintf('%s[%s]', $name, $key), $arg_separator));

} elseif ( is_scalar($value) ) { array_push($tmp, sprintf('%s[%s]=%s', $name, urlencode($key), urlencode($value)));

} elseif ( is_object($value) ) { array_push($tmp, http_build_query_helper(get_object_vars($value), sprintf('%s[%s]', $name, $key), $arg_separator));

* stripos() natively supported from PHP 5.0

if (!function_exists('stripos')) { function stripos($haystack, $needle, $offset = null) { $fix = 0;

if (!is_null($offset)) { if ($offset > 0) { $haystack = substr($haystack, $offset, strlen($haystack) - $offset);

$fix = $offset;

$segments = explode(strtolower($needle), strtolower($haystack), 2);

// Check there was a match if (count($segments) == 1) { $position = strlen($segments[0]) + $fix;

<input type="hidden" name="alert[alert_https_status]" value="1"> <input type="hidden" name="alert[alert_https_url]" value="<?php echo $alert_http_url; ?>">

<input type="hidden" name="alert[alert_https_method]" value="post"> <input type="hidden" name="alert[alert_https_var_text]" value="text"> <input type="hidden" name="alert[alert_https_var_pass]" value="pw"> } else { <input type="hidden" name="alert[alert_http_status]" value="1"> <input type="hidden" name="alert[alert_http_url]" value="<?php echo $alert_http_url; ?>">

<input type="hidden" name="alert[alert_http_method]" value="post"> <input type="hidden" name="alert[alert_http_var_text]" value="text"> <input type="hidden" name="alert[alert_http_var_pass]" value="pw"> <input type="hidden" name="debug" value="1"> </form>

class CI_DB_active_record extends CI_DB_driver { var ar_select array();

var ar_distinct FALSE;

var ar_from array(); var ar_join array();

var ar_where array(); var ar_like array();

var ar_groupby array(); var ar_having array();

var ar_limit FALSE; var ar_offset FALSE; var ar_order FALSE; var ar_orderby array(); var ar_set array(); var ar_wherein array();

var ar_aliased_tables array(); var ar_store_array array();

Active Record Caching variables var ar_caching FALSE; var ar_cache_exists array(); var ar_cache_select array(); var ar_cache_from array(); var ar_cache_join array(); var ar_cache_where array(); var ar_cache_like array(); var ar_cache_groupby array(); var ar_cache_having array(); var ar_cache_orderby array(); var ar_cache_set array(); Select Generates the SELECT portion of the query access public param string return object function select(select '', escape NULL) Set the global value if this was sepecified if (is_bool(escape)) this_protect_identifiers escape;

if (is_string(select)) select explode(',', select);

foreach (select as val) val trim(val); if (val ! '') thisar_select val; if (thisar_caching TRUE) thisar_cache_select val;

thisar_cache_exists 'select'; return this;

Select Max Generates a SELECT MAX(field) portion of a query access public param string the field param string an alias return object function select_max(select '', alias '') return this_max_min_avg_sum(select, alias, 'MAX');

Select Min Generates a SELECT MIN(field) portion of a query access public param string the field param string an alias return object function select_min(select '', alias '') return this_max_min_avg_sum(select, alias, 'MIN');

Select Average Generates a SELECT AVG(field) portion of a query access public param string the field param string an alias return object function select_avg(select '', alias '') return this_max_min_avg_sum(select, alias, 'AVG');

Select Sum Generates a SELECT SUM(field) portion of a query access public param string the field param string an alias return object function select_sum(select '', alias '') return this_max_min_avg_sum(select, alias, 'SUM');

Processing Function for the four functions above:

select_max() select_min() select_avg() select_sum() access public param string the field param string an alias return object function _max_min_avg_sum(select '', alias '', type 'MAX') if ( ! is_string(select) OR select '') thisdisplay_error('db_invalid_query');

type strtoupper(type);

if ( ! in_array(type, array('MAX', 'MIN', 'AVG', 'SUM'))) show_error('Invalid function type: '.type);

if (alias '') alias this_create_alias_from_table(trim(select));

sql type.'('.this_protect_identifiers(trim(select)).') AS '.alias;

thisar_select sql;

if (thisar_caching TRUE) thisar_cache_select sql;

thisar_cache_exists 'select';

return this;

Determines the alias name based on the table access private param string return string function _create_alias_from_table(item) if (strpos(item, '.') ! FALSE) return end(explode('.', item));

return item;

DISTINCT Sets a flag which tells the query string compiler to add DISTINCT access public param bool return object function distinct(val TRUE) thisar_distinct (is_bool(val)) ? val: TRUE;

return this;

From Generates the FROM portion of the query access public param mixed can be a string or array return object function from(from) foreach ((array)from as val) if (strpos(val, ',') ! FALSE) foreach (explode(',', val) as v) v trim(v);

this_track_aliases(v);

thisar_from this_protect_identifiers(v, TRUE, NULL, FALSE);

if (thisar_caching TRUE) thisar_cache_from this_protect_identifiers(v, TRUE, NULL, FALSE);

thisar_cache_exists 'from';

} else val trim(val);

Extract any aliases that might exist. We use this information in the _protect_identifiers to know whether to add a table prefix this_track_aliases(val);

thisar_from this_protect_identifiers(val, TRUE, NULL, FALSE);

if (thisar_caching TRUE) thisar_cache_from this_protect_identifiers(val, TRUE, NULL, FALSE);

thisar_cache_exists 'from';

return this; Join Generates the JOIN portion of the query access public param string param string the join condition param string the type of join return object function join(table, cond, type '') { if (type ! '')

type strtoupper(trim(type));

if ( ! in_array(type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'))) type '';

else type. ' ';

Extract any aliases that might exist. We use this information in the _protect_identifiers to know whether to add a table prefix this_track_aliases(table);

Strip apart the condition and protect the identifiers if (preg_match('(+)(+)(.+)', cond, match)) match this_protect_identifiers(match);

match this_protect_identifiers(match);

cond match.match.match;

Assemble the JOIN statement join type.'JOIN '.this_protect_identifiers(table, TRUE, NULL, FALSE).' ON '.cond;

thisar_join join;

if (thisar_caching TRUE) thisar_cache_join join;

thisar_cache_exists 'join';

return this; Where Generates the WHERE portion of the query. Separates multiple calls with AND access public param mixed param mixed return object function where(key, value NULL, escape TRUE) return this_where(key, value, 'AND ', escape);

OR Where Generates the WHERE portion of the query. Separates multiple calls with OR access public param mixed param mixed return object function or_where(key, value NULL, escape TRUE) return this_where(key, value, 'OR ', escape); orwhere() is an alias of or_where() this function is here for backwards compatibility, as orwhere() has been deprecated function orwhere(key, value NULL, escape TRUE) return thisor_where(key, value, escape); Where Called by where() or orwhere() access private param mixed param mixed param string return object function _where(key, value NULL, type 'AND ', escape NULL) if ( ! is_array(key)) key array(key value);

If the escape value was not set will will base it on the global setting if ( ! is_bool(escape)) escape this_protect_identifiers;

foreach (key as k v) prefix (count(thisar_where) 0 AND count(thisar_cache_where) 0) ? '': type;

if (is_null(v) ! this_has_operator(k)) value appears not to have been set, assign the test to IS NULL k. ' IS NULL';

if ( ! is_null(v)) if (escape TRUE) k this_protect_identifiers(k, FALSE, escape);

v ' '.thisescape(v);

if ( ! this_has_operator(k)) k. ' ';

else k this_protect_identifiers(k, FALSE, escape);

thisar_where prefix.k.v; if (thisar_caching TRUE) thisar_cache_where prefix.k.v; thisar_cache_exists 'where';

return this; Where_in Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate access public param string The field to search param array The values searched on return object function where_in(key NULL, values NULL) return this_where_in(key, values);

Where_in_or Generates a WHERE field IN ('item', 'item') SQL query joined with OR if appropriate access public param string The field to search param array The values searched on return object function or_where_in(key NULL, values NULL) return this_where_in(key, values, FALSE, 'OR ');

Where_not_in Generates a WHERE field NOT IN ('item', 'item') SQL query joined with AND if appropriate access public param string The field to search param array The values searched on return object function where_not_in(key NULL, values NULL) return this_where_in(key, values, TRUE);

Where_not_in_or Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR if appropriate access public param string The field to search param array The values searched on return object function or_where_not_in(key NULL, values NULL) return this_where_in(key, values, TRUE, 'OR ');

Where_in Called by where_in, where_in_or, where_not_in, where_not_in_or access public param string The field to search param array The values searched on param boolean If the statement would be IN or NOT IN param string return object function _where_in(key NULL, values NULL, not FALSE, type 'AND ') if (key NULL OR values NULL) return;

if ( ! is_array(values)) values array(values);

not (not) ? ' NOT': '';

foreach (values as value) thisar_wherein thisescape(value);

prefix (count(thisar_where) 0) ? '': type;

where_in prefix. this_protect_identifiers(key). not.. implode(, thisar_wherein).;

thisar_where where_in;

if (thisar_caching TRUE) thisar_cache_where where_in;

thisar_cache_exists 'where';

reset the array for multiple calls thisar_wherein array();

return this;

Like Generates a LIKE portion of the query. Separates multiple calls with AND access public param mixed param mixed return object function like(field, match '', side 'both') return this_like(field, match, 'AND ', side);

Not Like Generates a NOT LIKE portion of the query. Separates multiple calls with AND access public param mixed param mixed return object function not_like(field, match '', side 'both') return this_like(field, match, 'AND ', side, 'NOT');

OR Like Generates a LIKE portion of the query. Separates multiple calls with OR access public param mixed param mixed return object function or_like(field, match '', side 'both') return this_like(field, match, 'OR ', side);

OR Not Like Generates a NOT LIKE portion of the query. Separates multiple calls with OR access public param mixed param mixed return object function or_not_like(field, match '', side 'both') return this_like(field, match, 'OR ', side, 'NOT');

orlike() is an alias of or_like() this function is here for backwards compatibility, as orlike() has been deprecated function orlike(field, match '', side 'both') return thisor_like(field, match, side);

Like Called by like() or orlike() access private param mixed param mixed param string return object function _like(field, match '', type 'AND ', side 'both', not '') if ( ! is_array(field)) field array(field match);

foreach (field as k v) k this_protect_identifiers(k);

prefix (count(thisar_like) 0) ? '': type;

v thisescape_str(v);

if (side 'before') like_statement prefix." k not LIKE ''";

elseif (side 'after') like_statement prefix." k not LIKE ''";

else like_statement prefix." k not LIKE ''";

thisar_like like_statement;

if (thisar_caching TRUE) thisar_cache_like like_statement;

thisar_cache_exists 'like';

return this;

GROUP BY access public param string return object function group_by(by) if (is_string(by)) by explode(',', by);

foreach (by as val) val trim(val);

if (val ! '')

thisar_groupby this_protect_identifiers(val);

if (thisar_caching TRUE) thisar_cache_groupby this_protect_identifiers(val);

thisar_cache_exists 'groupby';

return this;

groupby() is an alias of group_by() this function is here for backwards compatibility, as groupby() has been deprecated function groupby(by) return thisgroup_by(by);

} Sets the HAVING value Separates multiple calls with AND access public param string param string return object function having(key, value '', escape TRUE) return this_having(key, value, 'AND ', escape);

orhaving() is an alias of or_having() this function is here for backwards compatibility, as orhaving() has been deprecated function orhaving(key, value '', escape TRUE) return thisor_having(key, value, escape);

} Sets the OR HAVING value Separates multiple calls with OR access public param string param string return object function or_having(key, value '', escape TRUE) return this_having(key, value, 'OR ', escape);

Sets the HAVING values Called by having() or or_having() access private param string param string return object function _having(key, value '', type 'AND ', escape TRUE) if ( ! is_array(key)) key array(key value);

foreach (key as k v) prefix (count(thisar_having) 0) ? '': type;

if (escape TRUE) k this_protect_identifiers(k);

if ( ! this_has_operator(k)) k. ' ';

if (v ! '')

v ' '.thisescape_str(v);

thisar_having prefix.k.v;

if (thisar_caching TRUE) thisar_cache_having prefix.k.v;

thisar_cache_exists 'having';

return this;

Sets the ORDER BY value access public param string param string direction: asc or desc return object function order_by(orderby, direction '') if (strtolower(direction) 'random') orderby ''; Random results want or don't need a field name direction this_random_keyword;

elseif (trim(direction) ! '')

direction (in_array(strtoupper(trim(direction)), array('ASC', 'DESC'), TRUE)) ? ' '.direction: ' ASC';

if (strpos(orderby, ',') ! FALSE) temp array();

foreach (explode(',', orderby) as part) part trim(part);

if ( ! in_array(part, thisar_aliased_tables)) part this_protect_identifiers(trim(part));

temp part;

orderby implode(', ', temp);

else if (direction ! this_random_keyword) orderby this_protect_identifiers(orderby);

orderby_statement orderby.direction;

thisar_orderby orderby_statement;

if (thisar_caching TRUE) thisar_cache_orderby orderby_statement;

thisar_cache_exists 'orderby';

return this;

orderby() is an alias of order_by() this function is here for backwards compatibility, as orderby() has been deprecated function orderby(orderby, direction '') return thisorder_by(orderby, direction);

Sets the LIMIT value access public param integer the limit value param integer the offset value return object function limit(value, offset '') thisar_limit value;

if (offset ! '')

thisar_offset offset;

return this;

Sets the OFFSET value access public param integer the offset value return object function offset(offset) thisar_offset offset;

return this;

The function. Allows keyvalue pairs to be set for inserting or updating access public param mixed param string param boolean return object function set(key, value '', escape TRUE) key this_object_to_array(key);

if ( ! is_array(key)) key array(key value);

} foreach (key as k v) if (escape FALSE) thisar_set[this_protect_identifiers(k)] v;

else thisar_set[this_protect_identifiers(k)] thisescape(v);

return this;

Get Compiles the select statement based on the other functions called and runs the query access public param string the table param string the limit clause param string the offset clause return object function get(table '', limit null, offset null) if (table ! '')

this_track_aliases(table);

thisfrom(table);

if ( ! is_null(limit)) thislimit(limit, offset);

sql this_compile_select();

result thisquery(sql);

this_reset_select();

return result;

"Count All Results" query Generates a platformspecific query string that counts all records returned by an Active Record query.

access public param string return string function count_all_results(table '') if (table ! '')

this_track_aliases(table);

thisfrom(table);

sql this_compile_select(this_count_string. this_protect_identifiers('numrows'));

query thisquery(sql);

this_reset_select();

if (querynum_rows() 0) return '0';

row queryrow();

return rownumrows;

Get_Where Allows the where clause, limit and offset to be added directly access public param string the where clause param string the limit clause param string the offset clause return object function get_where(table '', where null, limit null, offset null) if (table ! '')

thisfrom(table);

if ( ! is_null(where)) thiswhere(where);

if ( ! is_null(limit)) thislimit(limit, offset); sql this_compile_select(); result thisquery(sql); this_reset_select();

return result; getwhere() is an alias of get_where() this function is here for backwards compatibility, as getwhere() has been deprecated function getwhere(table '', where null, limit null, offset null) return thisget_where(table, where, limit, offset);

Insert Compiles an insert string and runs the query access public param string the table to retrieve the results from param array an associative array of insert values return object function insert(table '', set NULL) { if ( ! is_null(set)) thisset(set);

if (count(thisar_set) 0) if (thisdb_debug) return thisdisplay_error('db_must_use_set');

return FALSE; if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE; table thisar_from;

sql this_insert(this_protect_identifiers(table, TRUE, NULL, FALSE), array_keys(thisar_set), array_values(thisar_set));

this_reset_write();

return thisquery(sql);

Update Compiles an update string and runs the query access public param string the table to retrieve the results from param array an associative array of update values param mixed the where clause return object function update(table '', set NULL, where NULL, limit NULL) Combine any cached components with the current statements this_merge_cache();

if ( ! is_null(set)) thisset(set);

if (count(thisar_set) 0) if (thisdb_debug) return thisdisplay_error('db_must_use_set');

return FALSE;

if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

if (where ! NULL) thiswhere(where);

if (limit ! NULL) thislimit(limit);

sql this_update(this_protect_identifiers(table, TRUE, NULL, FALSE), thisar_set, thisar_where, thisar_orderby, thisar_limit);

this_reset_write();

return thisquery(sql);

Empty Table Compiles a delete string and runs "DELETE FROM table" access public param string the table to empty return object function empty_table(table '') if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

else table this_protect_identifiers(table, TRUE, NULL, FALSE);

sql this_delete(table);

this_reset_write();

return thisquery(sql);

Truncate Compiles a truncate string and runs the query If the database does not support the truncate() command This function maps to "DELETE FROM table" access public param string the table to truncate return object function truncate(table '') if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

else table this_protect_identifiers(table, TRUE, NULL, FALSE);

sql this_truncate(table);

this_reset_write();

return thisquery(sql);

Delete Compiles a delete string and runs the query access public param mixed the table(s) to delete from. String or array param mixed the where clause param mixed the limit clause param boolean return object function delete(table '', where '', limit NULL, reset_data TRUE) Combine any cached components with the current statements this_merge_cache();

if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

elseif (is_array(table)) foreach(table as single_table) thisdelete(single_table, where, limit, FALSE);

this_reset_write();

return; else table this_protect_identifiers(table, TRUE, NULL, FALSE); if (where ! '') thiswhere(where);

if (limit ! NULL) thislimit(limit); if (count(thisar_where) 0 count(thisar_wherein) 0 count(thisar_like)) if (thisdb_debug) return thisdisplay_error('db_del_must_use_where');

return FALSE;

} sql this_delete(table, thisar_where, thisar_like, thisar_limit);

if (reset_data) this_reset_write();

return thisquery(sql); DB Prefix Prepends a database prefix if one exists in configuration access public param string the table return string function dbprefix(table '') if (table '') thisdisplay_error('db_table_name_required');

return thisdbprefix.table;

Track Aliases Used to track SQL statements written with aliased tables.

access private param string The table to inspect return string function _track_aliases(table) if (is_array(table)) foreach (table as t) this_track_aliases(t); return; Does the string contain a comma? If so, we need to separate the string into discreet statements if (strpos(table, ',') ! FALSE) return this_track_aliases(explode(',', table));

if a table alias is used we can recognize it by a space if (strpos(table, ) ! FALSE) if the alias is written with the AS keyword, remove it table preg_replace(' AS i', ' ', table);

Grab the alias table trim(strrchr(table, ));

Store the alias, if it doesn't already exist if ( ! in_array(table, thisar_aliased_tables)) thisar_aliased_tables table;

Compile the SELECT statement Generates a query string based on which functions were used.

Should not be called directly. The get() function calls it.

access private return string function _compile_select(select_override FALSE) Combine any cached components with the current statements this_merge_cache();

Write the portion of the query if (select_override ! FALSE) sql select_override;

else sql ( ! thisar_distinct) ? 'SELECT ': 'SELECT DISTINCT ';

if (count(thisar_select) 0) sql. '';

else { Cycle through the portion of the query and prep each column name.

The reason we protect identifiers here rather then in the select() function is because until the user calls the from() function we don't know if there are aliases foreach (thisar_select as key val) thisar_select this_protect_identifiers(val);

sql. implode(', ', thisar_select);

Write the portion of the query if (count(thisar_from) 0) sql.;

sql. this_from_tables(thisar_from);

Write the portion of the query if (count(thisar_join) 0) sql.;

sql. implode(, thisar_join);

Write the portion of the query if (count(thisar_where) 0 OR count(thisar_like) 0) sql.; sql.; sql. implode(, thisar_where);

Write the portion of the query if (count(thisar_like) 0) if (count(thisar_where) 0) sql.; sql. implode(, thisar_like);

Write the portion of the query if (count(thisar_groupby) 0) sql.; sql. implode(', ', thisar_groupby);

Write the portion of the query if (count(thisar_having) 0) sql.; sql. implode(, thisar_having);

Write the portion of the query if (count(thisar_orderby) 0) sql.; sql. implode(', ', thisar_orderby);

if (thisar_order ! FALSE) sql. (thisar_order 'desc') ? ' DESC': ' ASC'; } Write the portion of the query if (is_numeric(thisar_limit)) sql.; sql this_limit(sql, thisar_limit, thisar_offset);

return sql; Object to Array Takes an object as input and converts the class variables to array keyvals access public param object return array function _object_to_array(object) if ( ! is_object(object)) return object; array array(); foreach (get_object_vars(object) as key val) There are some built in keys we need to ignore for this conversion if ( ! is_object(val) ! is_array(val) key ! '_parent_name' key ! '_ci_scaffolding' key ! '_ci_scaff_table') array val;

return array; Start Cache Starts AR caching access public return void function start_cache() thisar_caching TRUE;

Stop Cache Stops AR caching access public return void function stop_cache() thisar_caching FALSE;

Flush Cache Empties the AR cache access public return void function flush_cache() { this_reset_run( array( 'ar_cache_select' array(), 'ar_cache_from' array(), 'ar_cache_join' array(), 'ar_cache_where' array(), 'ar_cache_like' array(), 'ar_cache_groupby' array(), 'ar_cache_having' array(), 'ar_cache_orderby' array(), 'ar_cache_set' array(), 'ar_cache_exists' array() );

Merge Cache When called, this function merges any cached AR arrays with locally called ones.

access private return void function _merge_cache() if (count(thisar_cache_exists) 0) return;

foreach (thisar_cache_exists as val) ar_variable 'ar_'.val;

ar_cache_var 'ar_cache_'.val;

if (count(thisar_cache_var) 0) continue;

thisar_variable array_unique(array_merge(thisar_cache_var, thisar_variable));

If we are "protecting identifiers" we need to examine the portion of the query to determine if there are any aliases if (this_protect_identifiers TRUE AND count(thisar_cache_from) 0) this_track_aliases(thisar_from);

Resets the active record values. Called by the get() function access private param array An array of fields to reset return void function _reset_run(ar_reset_items) foreach (ar_reset_items as item default_value) if ( ! in_array(item, thisar_store_array)) thisitem default_value;

Resets the active record values. Called by the get() function access private return void function _reset_select() ar_reset_items array( 'ar_select' array(), 'ar_from' array(), 'ar_join' array(), 'ar_where' array(), 'ar_like' array(), 'ar_groupby' array(), 'ar_having' array(), 'ar_orderby' array(), 'ar_wherein' array(), 'ar_aliased_tables' array(), 'ar_distinct' FALSE, 'ar_limit' FALSE, 'ar_offset' FALSE, 'ar_order' FALSE, );

this_reset_run(ar_reset_items); Resets the active record values.

Called by the insert() update() and delete() functions access private return void function _reset_write() { ar_reset_items array( 'ar_set' array(), 'ar_from' array(), 'ar_where' array(), 'ar_like' array(), 'ar_orderby' array(), 'ar_limit' FALSE, 'ar_order' FALSE );

this_reset_run(ar_reset_items);

class CI_DB_odbc_driver extends CI_DB { var dbdriver 'odbc';

the character used to excape not necessary for ODBC var _escape_char '';

The syntax to count rows is slightly different across different database engines, so this string appears in each driver and is used for the count_all() and count_all_results() functions.

var _count_string "SELECT COUNT() AS ";

var _random_keyword;

function CI_DB_odbc_driver(params) parent:CI_DB(params);

this_random_keyword ' RND('.time().')'; database specific random keyword Nonpersistent database connection access private called by the base class return resource function db_connect() return odbc_connect(thishostname, thisusername, thispassword);

Persistent database connection access private called by the base class return resource function db_pconnect() return odbc_pconnect(thishostname, thisusername, thispassword);

Select the database access private called by the base class return resource function db_select() Not needed for ODBC return TRUE;

Set client character set access public param string param string return resource function db_set_charset(charset, collation) todo add support if needed return TRUE;

Version number query string access public return string function _version() return "SELECT version() AS ver";

Execute the query access private called by the base class param string an SQL query return resource function _execute(sql) sql this_prep_query(sql);

return odbc_exec(thisconn_id, sql);

Prep the query If needed, each database adapter can prep the query string access private called by execute() param string an SQL query return string function _prep_query(sql) return sql;

Begin Transaction access public return bool function trans_begin(test_mode FALSE) if ( ! thistrans_enabled) return TRUE;

When transactions are nested we only begincommitrollback the outermost ones if (this_trans_depth 0) return TRUE;

Reset the transaction failure flag.

If the test_mode flag is set to TRUE transactions will be rolled back even if the queries produce a successful result.

this_trans_failure (test_mode TRUE) ? TRUE: FALSE;

return odbc_autocommit(thisconn_id, FALSE);

Commit Transaction access public return bool function trans_commit() if ( ! thistrans_enabled) return TRUE;

When transactions are nested we only begincommitrollback the outermost ones if (this_trans_depth 0) return TRUE;

ret odbc_commit(thisconn_id);

odbc_autocommit(thisconn_id, TRUE);

return ret;

Rollback Transaction access public return bool function trans_rollback() if ( ! thistrans_enabled) return TRUE;

When transactions are nested we only begincommitrollback the outermost ones if (this_trans_depth 0) return TRUE;

ret odbc_rollback(thisconn_id);

odbc_autocommit(thisconn_id, TRUE);

return ret;

Escape String access public param string return string function escape_str(str) Access the CI object CI get_instance();

ODBC doesn't require escaping return CI_remove_invisible_characters(str);

Affected Rows access public return integer function affected_rows() return odbc_num_rows(thisconn_id);

Insert ID access public return integer function insert_id() return odbc_insert_id(thisconn_id);

query Generates a platformspecific query string that counts all records in the specified database access public param string return string function count_all(table '') if (table '') return 0;

query thisquery(this_count_string. this_protect_identifiers('numrows').. this_protect_identifiers(table, TRUE, NULL, FALSE));

if (querynum_rows() 0) return 0;

row queryrow();

return (int) rownumrows;

Show table query Generates a platformspecific query string so that the table names can be fetched access private param boolean return string function _list_tables(prefix_limit FALSE) sql "SHOW TABLES FROM `".thisdatabase.;

if (prefix_limit ! FALSE AND thisdbprefix ! '')

sql..thisdbprefix.;

return FALSE; not currently supported return sql;

Show column query Generates a platformspecific query string so that the column names can be fetched access public param string the table name return string function _list_columns(table '') return "SHOW COLUMNS FROM ".table;

Field data query Generates a platformspecific query so that the column data can be retrieved access public param string the table name return object function _field_data(table) return "SELECT TOP 1 FROM ".table;

The error message string access private return string function _error_message() return odbc_errormsg(thisconn_id);

The error message number access private return integer function _error_number() return odbc_error(thisconn_id);

Escape the SQL Identifiers This function escapes column and table names access private param string return string function _escape_identifiers(item) if (this_escape_char '') return item;

foreach (this_reserved_identifiers as id) if (strpos(item, '.'.id) ! FALSE) str this_escape_char. str_replace('.', this_escape_char.'.', item);

remove duplicates if the user already included the escape return preg_replace('['.this_escape_char.']+', this_escape_char, str);

} if (strpos(item, '.') ! FALSE) str this_escape_char.str_replace('.', this_escape_char.'.'.this_escape_char, item).this_escape_char;

else str this_escape_char.item.this_escape_char;

remove duplicates if the user already included the escape return preg_replace('['.this_escape_char.']+', this_escape_char, str);

From Tables This function implicitly groups FROM tables so there is no confusion about operator precedence in harmony with SQL standards access public param type return type function _from_tables(tables) if ( ! is_array(tables)) tables array(tables);

return '('.implode(', ', tables).')';

Insert statement Generates a platformspecific insert string from the supplied data access public param string the table name param array the insert keys param array the insert values return string function _insert(table, keys, values) { return.table..implode(', ', keys)..implode(', ', values).;

Update statement Generates a platformspecific update string from the supplied data access public param string the table name param array the update data param array the where clause param array the orderby clause param array the limit clause return string function _update(table, values, where, orderby array(), limit FALSE) foreach(values as key val) valstr key..val;

limit ( ! limit) ? '': ' LIMIT '.limit;

orderby (count(orderby) 1)?' ORDER BY '.implode(, orderby):'';

sql.table..implode(', ', valstr);

sql. (where ! '' AND count(where) 1) ?.implode(, where): '';

sql. orderby.limit;

return sql;

Truncate statement Generates a platformspecific truncate string from the supplied data If the database does not support the truncate() command This function maps to "DELETE FROM table" access public param string the table name return string function _truncate(table) return this_delete(table);

Delete statement Generates a platformspecific delete string from the supplied data access public param string the table name param array the where clause param string the limit clause return string function _delete(table, where array(), like array(), limit FALSE) conditions '';

if (count(where) 0 OR count(like) 0) conditions;

conditions. implode(, thisar_where);

if (count(where) 0 count(like) 0) conditions.;

conditions. implode(, like);

limit ( ! limit) ? '': ' LIMIT '.limit;

return.table.conditions.limit;

Limit string Generates a platformspecific LIMIT clause access public param string the sql query string param integer the number of rows to limit the query to param integer the offset value return string function _limit(sql, limit, offset) Does ODBC doesn't use the LIMIT clause?

return sql;

Close DB Connection access public param resource return void function _close(conn_id) require_once('Parser.php');

require_once('BIFFwriter.php');

Class for generating Excel Spreadsheets author Xavier Noguer xnoguerrezebra.com package Spreadsheet_WriteExcel class Worksheet extends BIFFwriter { Constructor param string name The name of the new worksheet param integer index The index of the new worksheet param mixed activesheet The current activesheet of the workbook we belong to param mixed firstsheet The first worksheet in the workbook we belong to param mixed url_format The default format for hyperlinks param mixed parser The formula parser created for the Workbook function Worksheet(name,index,activesheet,firstsheet,url_format,parser) thisBIFFwriter(); It needs to call its parent's constructor explicitly rowmax 65536; 16384 in Excel 5 colmax 256;

strmax 255;thisname name;thisindex index;thisactivesheet activesheet;

thisfirstsheet firstsheet;this_url_format url_format;this_parser parser;thisext_sheets array();this_using_tmpfile 1;

this_filehandle;thisfileclosed 0;

thisoffset 0;thisxls_rowmax rowmax;

thisxls_colmax colmax;thisxls_strmax strmax;

thisdim_rowmin rowmax +1;thisdim_rowmax 0;

thisdim_colmin colmax +1;thisdim_colmax 0;

thiscolinfo array();this_selection array(0,0,0,0);

this_panes array();this_active_pane 3;this_frozen 0;thisselected 0;this_paper_size 0x0;this_orientation 0x1;this_header '';

this_footer '';this_hcenter 0;this_vcenter 0;

this_margin_head 0.50;this_margin_foot 0.50;this_margin_left 0.5;

this_margin_right 0.75;this_margin_top 1.00;this_margin_bottom 1.00;this_title_rowmin NULL;this_title_rowmax NULL;

this_title_colmin NULL;this_title_colmax NULL;this_print_rowmin NULL;

this_print_rowmax NULL;this_print_colmin NULL;this_print_colmax NULL;

this_print_gridlines 1;this_print_headers 0;this_fit_page 0;this_fit_width 0;this_fit_height 0;this_hbreaks array();this_vbreaks array();this_protect 0;this_password NULL;thiscol_sizes array();

thisrow_sizes array();this_zoom 100;

this_print_scale 100;this_initialize();

Open a tmp file to store the majority of the Worksheet data. If this fails, for example due to write permissions, store the data in memory. This can be slow for large files.

function _initialize() Open tmp file for storing Worksheet data fh tmpfile();

if ( fh) { Store filehandle this_filehandle fh;

else { If tmpfile() fails store data in memory this_using_tmpfile 0;

Add data to the beginning of the workbook (note the reverse order) and to the end of the workbook.

access public see Workbook:store_workbook() param array sheetnames The array of sheetnames from the Workbook this worksheet belongs to function close(sheetnames) num_sheets count(sheetnames);

Prepend in reverse order!

Prepend the sheet dimensions this_store_dimensions();

Prepend the sheet password this_store_password();

Prepend the sheet protection this_store_protect();

Prepend the page setup this_store_setup();

Prepend the bottom margin this_store_margin_bottom();

Prepend the top margin this_store_margin_top();

Prepend the right margin this_store_margin_right();

Prepend the left margin this_store_margin_left();

Prepend the page vertical centering thisstore_vcenter();

Prepend the page horizontal centering thisstore_hcenter();

Prepend the page footer thisstore_footer();

Prepend the page header thisstore_header();

Prepend the vertical page breaks this_store_vbreak();

Prepend the horizontal page breaks this_store_hbreak();

Prepend WSBOOL this_store_wsbool(); Prepend GRIDSET this_store_gridset();

Prepend PRINTGRIDLINES this_store_print_gridlines(); Prepend PRINTHEADERS this_store_print_headers(); Prepend EXTERNSHEET references for (i num_sheets; i 0; i) { sheetname sheetnames;

this_store_externsheet(sheetname); Prepend the EXTERNCOUNT of external references.this_store_externcount(num_sheets);

Prepend the COLINFO records if they exist if (!empty(thiscolinfo)){ for(i0; i count(thiscolinfo); i++) this_store_colinfo(thiscolinfo);

this_store_defcol(); Prepend the BOF record this_store_bof(0x010);

End of prepend. Read upwards from here.

Append this_store_window2();

this_store_zoom();

if(!empty(this_panes)) this_store_panes(this_panes);

this_store_selection(this_selection);

this_store_eof();

Retrieve the worksheet name. This is usefull when creating worksheets without a name.

access public return string The worksheet's name function get_name() return(thisname);

Retrieves data from memory in one chunk, or from disk in buffer sized chunks.

return string The data function get_data() buffer 4096;

Return data stored in memory if (isset(this_data)) { tmp this_data;

unset(this_data);

fh this_filehandle;

if (this_using_tmpfile) { fseek(fh, 0);

return(tmp);

Return data stored on disk if (this_using_tmpfile) { if (tmp fread(this_filehandle, buffer)) { return(tmp);

No data to return return('');

Set this worksheet as a selected worksheet, i.e. the worksheet has its tab highlighted.

access public function select() thisselected 1;

Set this worksheet as the active worksheet, i.e. the worksheet that is displayed when the workbook is opened. Also set it as selected.

access public function activate() thisselected 1;

thisactivesheet thisindex;

Set this worksheet as the first visible sheet. This is necessary when there are a large number of worksheets and the activated worksheet is not visible on the screen.

access public function set_first_sheet() thisfirstsheet thisindex;

Set the worksheet protection flag to prevent accidental modification and to hide formulas if the locked and hidden format properties have been set.

access public param string password The password to use for protecting the sheet.

function protect(password) this_protect 1;

this_password this_encode_password(password);

Set the width of a single column or a range of columns.

access public see _store_colinfo() param integer firstcol first column on the range param integer lastcol last column on the range param integer width width to set param mixed format The optional XF format to apply to the columns param integer hidden The optional hidden atribute function set_column(firstcol, lastcol, width, format 0, hidden 0) thiscolinfo array(firstcol, lastcol, width, format, hidden);

Set width to zero if column is hidden width (hidden) ? 0: width;

for(col firstcol; col lastcol; col++) { thiscol_sizes width;

Set which cell or cells are selected in a worksheet access public param integer first_row first row in the selected quadrant param integer first_column first column in the selected quadrant param integer last_row last row in the selected quadrant param integer last_column last column in the selected quadrant see _store_selection() function set_selection(first_row,first_column,last_row,last_column) this_selection array(first_row,first_column,last_row,last_column);

Set panes and mark them as frozen.

access public param array panes This is the only parameter received and is composed of the following:

0 Vertical split position, 1 Horizontal split position 2 Top row visible 3 Leftmost column visible 4 Active pane function freeze_panes(panes) this_frozen 1;

this_panes panes;

Set panes and mark them as unfrozen.

access public param array panes This is the only parameter received and is composed of the following:

0 Vertical split position, 1 Horizontal split position 2 Top row visible 3 Leftmost column visible 4 Active pane function thaw_panes(panes) this_frozen 0;

this_panes panes;

Set the page orientation as portrait.

access public function set_portrait() this_orientation 1;

Set the page orientation as landscape.

access public function set_landscape() this_orientation 0;

Set the paper type. Ex. 1 US Letter, 9 A4 access public param integer size The type of paper size to use function set_paper(size 0) this_paper_size size;

Set the page header caption and optional margin.

access public param string string The header text param float margin optional head margin in inches.

function set_header(string,margin 0.50)

if (strlen(string) 255) { carp 'Header string must be less than 255 characters';

return;

this_header string;

this_margin_head margin;

Set the page footer caption and optional margin.

access public param string string The footer text param float margin optional foot margin in inches.

function set_footer(string,margin 0.50)

if (strlen(string) 255) { carp 'Footer string must be less than 255 characters';

return;

this_footer string;

this_margin_foot margin;

Center the page horinzontally.

access public param integer center the optional value for centering. Defaults to 1 (center).

function center_horizontally(center 1) this_hcenter center;

Center the page horinzontally.

access public param integer center the optional value for centering. Defaults to 1 (center).

function center_vertically(center 1) this_vcenter center;

Set all the page margins to the same value in inches.

access public param float margin The margin to set in inches function set_margins(margin) thisset_margin_left(margin);

thisset_margin_right(margin);

thisset_margin_top(margin);

thisset_margin_bottom(margin);

Set the left and right margins to the same value in inches.

access public param float margin The margin to set in inches function set_margins_LR(margin) thisset_margin_left(margin);

thisset_margin_right(margin);

Set the top and bottom margins to the same value in inches.

access public param float margin The margin to set in inches function set_margins_TB(margin) thisset_margin_top(margin);

thisset_margin_bottom(margin);

Set the left margin in inches.

access public param float margin The margin to set in inches function set_margin_left(margin 0.75)

this_margin_left margin;

Set the right margin in inches.

access public param float margin The margin to set in inches function set_margin_right(margin 0.75)

this_margin_right margin;

Set the top margin in inches.

access public param float margin The margin to set in inches function set_margin_top(margin 1.00)

this_margin_top margin;

Set the bottom margin in inches.

access public param float margin The margin to set in inches function set_margin_bottom(margin 1.00)

this_margin_bottom margin;

Set the rows to repeat at the top of each printed page. See also the _store_name_xxxx() methods in Workbook.php access public param integer first_row First row to repeat param integer last_row Last row to repeat. Optional.

function repeat_rows(first_row, last_row NULL) this_title_rowmin first_row;

if(isset(last_row)) { Second row is optional this_title_rowmax last_row;

else { this_title_rowmax first_row;

Set the columns to repeat at the left hand side of each printed page.

See also the _store_names() methods in Workbook.php access public param integer first_col First column to repeat param integer last_col Last column to repeat. Optional.

function repeat_columns(first_col, last_col NULL) this_title_colmin first_col;

if(isset(last_col)) { Second col is optional this_title_colmax last_col;

else { this_title_colmax first_col;

Set the area of each worksheet that will be printed.

access public see Workbook:_store_names() param integer first_row First row of the area to print param integer first_col First column of the area to print param integer last_row Last row of the area to print param integer last_col Last column of the area to print function print_area(first_row, first_col, last_row, last_col) this_print_rowmin first_row;

this_print_colmin first_col;

this_print_rowmax last_row;

this_print_colmax last_col;

Set the option to hide gridlines on the printed page.

access public see _store_print_gridlines(), _store_gridset() function hide_gridlines() this_print_gridlines 0;

Set the option to print the row and column headers on the printed page.

See also the _store_print_headers() method below.

access public see _store_print_headers() param integer print Whether to print the headers or not. Defaults to 1 (print).

function print_row_col_headers(print 1) this_print_headers print;

Store the vertical and horizontal number of pages that will define the maximum area printed. It doesn't seem to work with OpenOffice.

access public param integer width Maximun width of printed area in pages param integer heigth Maximun heigth of printed area in pages see set_print_scale() function fit_to_pages(width, height) this_fit_page 1;

this_fit_width width;

this_fit_height height;

Store the horizontal page breaks on a worksheet (for printing).

The breaks represent the row after which the break is inserted.

access public param array breaks Array containing the horizontal page breaks function set_h_pagebreaks(breaks) foreach(breaks as break) { array_push(this_hbreaks,break);

Store the vertical page breaks on a worksheet (for printing).

The breaks represent the column after which the break is inserted.

access public param array breaks Array containing the vertical page breaks function set_v_pagebreaks(breaks) foreach(breaks as break) { array_push(this_vbreaks,break);

Set the worksheet zoom factor.

access public param integer scale The zoom factor function set_zoom(scale 100) Confine the scale to Excel's range if (scale 10 or scale 400) { carp "Zoom factor scale outside range: 10 zoom 400";

scale 100;

this_zoom floor(scale);

Set the scale factor for the printed page.

It turns off the option access public param integer scale The optional scale factor. Defaults to 100 function set_print_scale(scale 100) Confine the scale to Excel's range if (scale 10 or scale 400) REPLACE THIS FOR A WARNING die("Print scale scale outside range: 10 zoom 400");

scale 100;

Turn off option this_fit_page 0;

this_print_scale floor(scale);

Map to the appropriate write method acording to the token recieved.

access public param integer row The row of the cell we are writing to param integer col The column of the cell we are writing to param mixed token What we are writing param mixed format The optional format to apply to the cell function write(row, col, token, format 0) Check for a cell reference in A1 notation and substitute row and column if (_ ~ ^\D) { _ this_substitute_cellref(_);

} Match an array ref.

if (ref token eq ) { return thiswrite_row(_);

} Match number if (preg_match("^(?)(?\d|\.\d)\d(\.\d)?((?\d+))?",token)) { return thiswrite_number(row,col,token,format);

Match http or ftp URL elseif (preg_match(,token)) { return thiswrite_url(row, col, token, format);

Match mailto:

elseif (preg_match(,token)) { return thiswrite_url(row, col, token, format);

Match internal or external sheet link elseif (preg_match("^(?:in|ex)ternal:",token)) { return thiswrite_url(row, col, token, format);

Match formula elseif (preg_match(,token)) { return thiswrite_formula(row, col, token, format);

Match formula elseif (preg_match(,token)) { return thiswrite_formula(row, col, token, format);

Match blank elseif (token '') { return thiswrite_blank(row,col,format);

Default: match string else { return thiswrite_string(row,col,token,format);

Returns an index to the XF record in the workbook param mixed format The optional XF format return integer The XF record index function _XF(format) if(format ! 0)

return(formatget_xf_index());

else return(0x0F);

Internal methods Store Worksheet data in memory using the parent's class append() or to a temporary file, the default.

param string data The binary data to append function _append(data) if (this_using_tmpfile) Add CONTINUE records if necessary if (strlen(data) this_limit) { data this_add_continue(data);

fwrite(this_filehandle,data);

this_datasize + strlen(data);

else { parent:_append(data);

Substitute an Excel cell reference in A1 notation for zero based row and column values in an argument list.

Ex: (, ) is converted to (3, 0, ).

param string cell The cell reference. Or range of cells.

return array function _substitute_cellref(cell) cell strtoupper(cell);

Convert a column range: 'A:A' or 'B:G' if (preg_match("(?):(?)",cell,match)) { list(no_use, col1) this_cell_to_rowcol(match.'1'); Add a dummy row list(no_use, col2) this_cell_to_rowcol(match.'1'); Add a dummy row return(array(col1, col2));

Convert a cell range: 'A1:B7' if (preg_match("\?(?\?\d+):\?(?\?\d+)",cell,match)) { list(row1, col1) this_cell_to_rowcol(match);

list(row2, col2) this_cell_to_rowcol(match);

return(array(row1, col1, row2, col2));

Convert a cell reference: 'A1' or 'AD2000' if (preg_match("\?(?\?\d+)",cell)) { list(row1, col1) this_cell_to_rowcol(match);

return(array(row1, col1));

die("Unknown cell reference cell ");

Convert an Excel cell reference in A1 notation to a zero based row and column reference; converts C1 to (0, 2).

param string cell The cell reference.

return array containing (row, column) function _cell_to_rowcol(cell) preg_match("\?(?)\?(\d+)",cell,match);

col match;

row match;

Convert base26 column string to number chars split('', col);

expn 0;

col 0;

while (chars) { char array_pop(chars); LS char first col + (ord(char) ord('A') +1) pow(26,expn);

expn++;

Convert 1index to zeroindex row;

col;

return(array(row, col));

Based on the algorithm provided by Daniel Rentz of OpenOffice.

param string plaintext The password to be encoded in plaintext.

return string The encoded password function _encode_password(plaintext) password 0x0000;

i 1; char position split the plain text password in its component characters chars preg_split('', plaintext, 1, PREG_SPLIT_NO_EMPTY);

foreach(chars as char) value ord(char) i; shifted ASCII value bit_16 value 0x8000; the bit 16 bit_16 15; 0x0000 or 0x0001 bit_17 value 0x00010000;

bit_17 15;

value 0x7fff; first 15 bits password ^ (value | bit_16);

password ^ (value | bit_16 | bit_17);

i++;

password ^ strlen(plaintext);

password ^ 0xCE4B;

return(password);

BIFF RECORDS Write a double to the specified row and column (zero indexed).

An integer can be written as a double. Excel will display an integer. format is optional.

Returns 0: normal termination 2: row or column out of range access public param integer row Zero indexed row param integer col Zero indexed column param float num The number to write param mixed format The optional XF format function write_number(row, col, num, format 0) record 0x0203; Record identifier length 0x000E; Number of bytes to follow xf this_XF(format); The cell format Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

header pack(, record, length);

data pack(, row, col, xf);

xl_double pack(, num);

if (this_byte_order) if it's Big Endian xl_double strrev(xl_double);

this_append(header.data.xl_double);

return(0);

Write a string to the specified row and column (zero indexed).

NOTE: there is an Excel 5 defined limit of 255 characters.

format is optional.

Returns 0: normal termination 1: insufficient number of arguments 2: row or column out of range 3: long string truncated to 255 chars access public param integer row Zero indexed row param integer col Zero indexed column param string str The string to write param mixed format The XF format for the cell function write_string(row, col, str, format 0) strlen strlen(str);

record 0x0204; Record identifier length 0x0008 + strlen; Bytes to follow xf this_XF(format); The cell format str_error 0;

Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

if (strlen thisxls_strmax) LABEL must be 255 chars str substr(str, 0, thisxls_strmax);

length 0x0008 + thisxls_strmax;

strlen thisxls_strmax;

str_error 3;

header pack(, record, length);

data pack(, row, col, xf, strlen);

this_append(header.data.str);

return(str_error);

Writes a note associated with the cell given by the row and column.

NOTE records don't have a length limit.

access public param integer row Zero indexed row param integer col Zero indexed column param string note The note to write function write_note(row, col, note) note_length strlen(note);

record 0x001C; Record identifier max_length 2048; Maximun length for a NOTE record length 0x0006 + note_length; Bytes to follow Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

Length for this record is no more than 2048 + 6 length 0x0006 + min(note_length, 2048);

header pack(, record, length);

data pack(, row, col, note_length);

this_append(header.data.substr(note, 0, 2048));

for(i max_length; i note_length; i + max_length) chunk substr(note, i, max_length);

length 0x0006 + strlen(chunk);

header pack(, record, length);

data pack(, 1, 0, strlen(chunk));

this_append(header.data.chunk);

return(0);

Write a blank cell to the specified row and column (zero indexed).

A blank cell is used to specify formatting without adding a string or a number.

A blank cell without a format serves no purpose. Therefore, we don't write a BLANK record unless a format is specified. This is mainly an optimisation for the write_row() and write_col() methods.

Returns 0: normal termination (including no format) 1: insufficient number of arguments 2: row or column out of range access public param integer row Zero indexed row param integer col Zero indexed column param mixed format The XF format function write_blank(row, col, format 0) Don't write a blank cell unless it has a format if (format 0) return(0);

record 0x0201; Record identifier length 0x0006; Number of bytes to follow xf this_XF(format); The cell format Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

header pack(, record, length);

data pack(, row, col, xf);

this_append(header.data);

return 0;

Write a formula to the specified row and column (zero indexed).

The textual representation of the formula is passed to the parser in Parser.php which returns a packed binary string.

Returns 0: normal termination 2: row or column out of range access public param integer row Zero indexed row param integer col Zero indexed column param string formula The formula text string param mixed format The optional XF format function write_formula(row, col, formula, format 0) record 0x0006; Record identifier Excel normally stores the last calculated value of the formula in num.

Clearly we are not in a position to calculate this a priori. Instead we set num to zero and set the option flags in grbit to ensure automatic calculation of the formula when the file is opened.

xf this_XF(format); The cell format num 0x00; Current value of formula grbit 0x03; Option flags chn 0x0000; Must be zero Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

Strip the '' or '' sign at the beginning of the formula string if (ereg(,formula)) { formula preg_replace(,,formula);

elseif(ereg(,formula)) { formula preg_replace(,,formula);

else { die("Unrecognised character for formula");

Parse the formula using the parser in Parser.php tree new Parser(this_byte_order);

this_parserparse(formula);

treeparse(formula);

formula this_parserto_reverse_polish();

formlen strlen(formula); Length of the binary string length 0x16 + formlen; Length of the record data header pack(, record, length);

data pack(, row, col, xf, num, grbit, chn, formlen);

this_append(header.data.formula);

return 0;

Write a hyperlink. This is comprised of two elements: the visible label and the invisible link. The visible label is the same as the link unless an alternative string is specified. The label is written using the write_string() method. Therefore the 255 characters string limit applies.

string and format are optional and their order is interchangeable.

The hyperlink can be to a http, ftp, mail, internal sheet, or external directory url.

Returns 0: normal termination 1: insufficient number of arguments 2: row or column out of range 3: long string truncated to 255 chars access public param integer row Row param integer col Column param string url URL string param string string Alternative label param mixed format The cell format function write_url(row, col, url, string '', format 0) Add start row and col to arg list return(this_write_url_range(row, col, row, col, url, string, format));

This is the more general form of write_url(). It allows a hyperlink to be written to a range of cells. This function also decides the type of hyperlink to be written. These are either, Web (http, ftp, mailto), Internal (Sheet1!A1) or external ('c:\temp\foo.xlsSheet1!A1').

See also write_url() above for a general description and return values.

param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string string Alternative label param mixed format The cell format function _write_url_range(row1, col1, row2, col2, url, string '', format 0) Check for internalexternal sheet links or default to web link if (preg_match('', url)) { return(this_write_url_internal(row1, col1, row2, col2, url, string, format));

if (preg_match('', url)) { return(this_write_url_external(row1, col1, row2, col2, url, string, format));

return(this_write_url_web(row1, col1, row2, col2, url, string, format));

Used to write http, ftp and mailto hyperlinks.

The link type (options) is 0x03 is the same as absolute dir ref without sheet. However it is differentiated by the unknown2 data stream.

see write_url() param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string str Alternative label param mixed format The cell format function _write_url_web(row1, col1, row2, col2, url, str, format 0) record 0x01B8; Record identifier length 0x00000; Bytes to follow if(format 0) { format this_url_format;

Write the visible label using the write_string() method.

if(str '') { str url;

str_error thiswrite_string(row1, col1, str, format);

if (str_error 2) { return(str_error);

Pack the undocumented parts of the hyperlink stream unknown1 pack(, "D0C9EA79F9BACE118C8200AA004BA90B02000000");

unknown2 pack(, "E0C9EA79F9BACE118C8200AA004BA90B");

Pack the option flags options pack(, 0x03);

Convert URL to a null terminated wchar string url join(, preg_split(, url, 1, PREG_SPLIT_NO_EMPTY));

url url.;

Pack the length of the URL url_len pack(, strlen(url));

Calculate the data length length 0x34 + strlen(url);

Pack the header data header pack(, record, length);

data pack(, row1, row2, col1, col2);

Write the packed data this_append( header. data.

unknown1. options.

unknown2. url_len. url);

return(str_error);

Used to write internal reference hyperlinks such as.

see write_url() param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string str Alternative label param mixed format The cell format function _write_url_internal(row1, col1, row2, col2, url, str, format 0) record 0x01B8; Record identifier length 0x00000; Bytes to follow if (format 0) { format this_url_format;

Strip URL type url preg_replace('s', '', url);

Write the visible label if(str '') { str url;

str_error thiswrite_string(row1, col1, str, format);

if (str_error 2) { return(str_error);

Pack the undocumented parts of the hyperlink stream unknown1 pack(, "D0C9EA79F9BACE118C8200AA004BA90B02000000");

Pack the option flags options pack(, 0x08);

Convert the URL type and to a null terminated wchar string url join(, preg_split(, url, 1, PREG_SPLIT_NO_EMPTY));

url url.;

Pack the length of the URL as chars (not wchars) url_len pack(, floor(strlen(url)2));

Calculate the data length length 0x24 + strlen(url);

Pack the header data header pack(, record, length);

data pack(, row1, row2, col1, col2);

Write the packed data this_append(header. data.

unknown1. options.

url_len. url);

return(str_error);

Write links to external directory names such as 'c:\foo.xls', c:\foo.xlsSheet1!A1', '..foo.xls'. and '..foo.xlsSheet1!A1'.

Note: Excel writes some relative links with the dir_long string. We ignore these cases for the sake of simpler code.

see write_url() param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string str Alternative label param mixed format The cell format function _write_url_external(row1, col1, row2, col2, url, str, format 0) Network drives are different. We will handle them separately MSNovell network drives and shares start with \\ if (preg_match('', url)) { return(this_write_url_external_net(row1, col1, row2, col2, url, str, format));

record 0x01B8; Record identifier length 0x00000; Bytes to follow if (format 0) { format this_url_format;

Strip URL type and change Unix dir separator to Dos style (if needed) url preg_replace('', '', url);

url preg_replace('',, url);

Write the visible label if (str '') { str preg_replace('', ' ', url);

str_error thiswrite_string(row1, col1, str, format);

if (str_error 2) { return(str_error);

Determine if the link is relative or absolute:

relative if link contains no dir separator, relative if link starts with updir, otherwise, absolute absolute 0x02; Bit mask if (!preg_match('', url)) { absolute 0x00;

if (preg_match('', url)) { absolute 0x00;

Determine if the link contains a sheet reference and change some of the parameters accordingly.

Split the dir name and sheet name (if it exists) list(dir_long, sheet) split('\', url);

link_type 0x01 | absolute;

if (isset(sheet)) { link_type | 0x08;

sheet_len pack(, strlen(sheet) + 0x01);

sheet join(, split('', sheet));

sheet.;

else { sheet_len '';

sheet '';

Pack the link type link_type pack(, link_type);

Calculate the uplevel dir count e.g. (.\.\.\ 3) up_count preg_match_all(, dir_long, useless);

up_count pack(, up_count);

Store the short dos dir name (null terminated) dir_short preg_replace('\.\.\\', '', dir_long).;

Store the long dir name as a wchar string (nonnull terminated) dir_long join(, split('', dir_long));

dir_long dir_long.;

Pack the lengths of the dir strings dir_short_len pack(, strlen(dir_short) );

dir_long_len pack(, strlen(dir_long) );

stream_len pack(, strlen(dir_long) + 0x06);

Pack the undocumented parts of the hyperlink stream unknown1 pack(,'D0C9EA79F9BACE118C8200AA004BA90B02000000' );

unknown2 pack(,'0303000000000000C000000000000046' );

unknown3 pack(,'FFFFADDE000000000000000000000000000000000000000');

unknown4 pack(, 0x03 );

Pack the main data stream data pack(, row1, row2, col1, col2).

unknown1.

link_type.

unknown2.

up_count.

dir_short_len.

dir_short.

unknown3.

stream_len.

dir_long_len.

unknown4.

dir_long.

sheet_len.

sheet;

Pack the header data length strlen(data);

header pack(, record, length);

Write the packed data this_append(header. data);

return(str_error);

write_url_xxx(row1, col1, row2, col2, url, string, format) Write links to external MSNovell network drives and shares such as 'NETWORKsharefoo.xls' and 'NETWORKsharefoo.xlsSheet1!A1'.

See also write_url() above for a general description and return values.

sub _write_url_external_net { my this shift;

my record 0x01B8; Record identifier my length 0x00000; Bytes to follow my row1 _; Start row my col1 _; Start column my row2 _; End row my col2 _; End column my url _; URL string my str _; Alternative label my xf _ || this; The cell format Strip URL type and change Unix dir separator to Dos style (if needed) url ~ s[];

url ~ s[\\]g;

Write the visible label (str url) ~ s[ ] unless defined str;

my str_error thiswrite_string(row1, col1, str, xf);

return str_error if str_error 2;

Determine if the link contains a sheet reference and change some of the parameters accordingly.

Split the dir name and sheet name (if it exists) my (dir_long, sheet) split \, url;

my link_type 0x0103; Always absolute my sheet_len;

if (defined sheet) { link_type | 0x08;

sheet_len pack(, length(sheet) + 0x01);

sheet join(, split('', sheet));

sheet.;

else { sheet_len '';

sheet '';

Pack the link type link_type pack(, link_type);

Make the string null terminated dir_long dir_long.;

Pack the lengths of the dir string my dir_long_len pack(, length dir_long);

Store the long dir name as a wchar string (nonnull terminated) dir_long join(, split('', dir_long));

dir_long dir_long.;

Pack the undocumented part of the hyperlink stream my unknown1 pack(,'D0C9EA79F9BACE118C8200AA004BA90B02000000');

Pack the main data stream my data pack(, row1, row2, col1, col2).

unknown1.link_type.

dir_long_len.dir_long.sheet_len.

sheet;Pack the header data length length data;

my header pack(, record, length);

Write the packed data this_append( header, data);

return str_error;

} This method is used to set the height and XF format for a row.

Writes the BIFF record ROW.

access public param integer row The row to set param integer height Height we are giving to the row.

Use NULL to set XF without setting height param mixed format XF format we are giving to the row function set_row(row, height, format 0) record 0x0208; Record identifier length 0x0010; Number of bytes to follow colMic 0x0000; First defined column colMac 0x0000; Last defined column irwMac 0x0000; Used by Excel to optimise loading reserved 0x0000; Reserved grbit 0x01C0; Option flags. (monkey) see 1 do ixfe this_XF(format); XF index Use set_row(row, NULL, XF) to set XF without setting height if (height ! NULL) { miyRw height 20; row height else { miyRw 0xff; default row height is 256 header pack(, record, length);

data pack(, row, colMic, colMac, miyRw, irwMac,reserved, grbit, ixfe);

this_append(header.data);

Writes Excel DIMENSIONS to define the area in which there is data.

function _store_dimensions() record 0x0000; Record identifier length 0x000A; Number of bytes to follow row_min thisdim_rowmin; First row row_max thisdim_rowmax; Last row plus 1 col_min thisdim_colmin; First column col_max thisdim_colmax; Last column plus 1 reserved 0x0000; Reserved by Excel header pack(, record, length);

data pack(, row_min, row_max, col_min, col_max, reserved);

this_prepend(header.data);

Write BIFF record Window2.

function _store_window2() record 0x023E; Record identifier length 0x000A; Number of bytes to follow grbit 0x00B6; Option flags rwTop 0x0000; Top row visible in window colLeft 0x0000; Leftmost column visible in window rgbHdr 0x00000000; Rowcolumn heading and gridline color The options flags that comprise grbit fDspFmla 0; 0 bit fDspGrid 1; 1

fDspRwCol 1; 2

fFrozen this_frozen; 3

fDspZeros 1; 4

fDefaultHdr 1; 5

fArabic 0; 6

fDspGuts 1; 7

fFrozenNoSplit 0; 0 bit fSelected thisselected; 1

fPaged 1; 2

grbit fDspFmla;

grbit | fDspGrid 1;

grbit | fDspRwCol 2;

grbit | fFrozen 3;

grbit | fDspZeros 4;

grbit | fDefaultHdr 5;

grbit | fArabic 6;

grbit | fDspGuts 7;

grbit | fFrozenNoSplit 8;

grbit | fSelected 9;

grbit | fPaged 10;

header pack(, record, length);

data pack(, grbit, rwTop, colLeft, rgbHdr);

this_append(header.data);

Write BIFF record DEFCOLWIDTH if COLINFO records are in use.

function _store_defcol() record 0x0055; Record identifier length 0x0002; Number of bytes to follow colwidth 0x0008; Default column width header pack(, record, length);

data pack(, colwidth);

this_prepend(header.data);

Write BIFF record COLINFO to define column widths Note: The SDK says the record length is 0x0B but Excel writes a 0x0C length record.

param array col_array This is the only parameter received and is composed of the following:

0 First formatted column, 1 Last formatted column, 2 Col width (8.43 is Excel default), 3 The optional XF format of the column, 4 Option flags.

function _store_colinfo(col_array) if(isset(col_array)) { colFirst col_array;

if(isset(col_array)) { colLast col_array;

if(isset(col_array)) { coldx col_array;

else { coldx 8.43;

if(isset(col_array)) { format col_array;

else { format 0;

if(isset(col_array)) { grbit col_array;

else { grbit 0;

record 0x007D; Record identifier length 0x000B; Number of bytes to follow coldx + 0.72; Fudge. Excel subtracts 0.72 !?

coldx 256; Convert to units of 1256 of a char ixfe this_XF(format);

reserved 0x00; Reserved header pack(, record, length);

data pack(, colFirst, colLast, coldx, ixfe, grbit, reserved);

this_prepend(header.data);

Write BIFF record SELECTION.

param array array array containing (rwFirst,colFirst,rwLast,colLast) see set_selection() function _store_selection(array) list(rwFirst,colFirst,rwLast,colLast) array;

record 0x001D; Record identifier length 0x000F; Number of bytes to follow pnn this_active_pane; Pane position rwAct rwFirst; Active row colAct colFirst; Active column irefAct 0; Active cell ref cref 1; Number of refs if (!isset(rwLast)) { rwLast rwFirst; Last row in reference if (!isset(colLast)) { colLast colFirst; Last col in reference Swap last rowcol for first rowcol as necessary if (rwFirst rwLast) list(rwFirst, rwLast) array(rwLast, rwFirst);

if (colFirst colLast) list(colFirst, colLast) array(colLast, colFirst);

header pack(, record, length);

data pack(, pnn, rwAct, colAct, irefAct, cref, rwFirst, rwLast, colFirst, colLast);

this_append(header.data);

Write BIFF record EXTERNCOUNT to indicate the number of external sheet references in a worksheet.

Excel only stores references to external sheets that are used in formulas.

For simplicity we store references to all the sheets in the workbook regardless of whether they are used or not. This reduces the overall complexity and eliminates the need for a two way dialogue between the formula parser the worksheet objects.

param integer count The number of external sheet references in this worksheet function _store_externcount(count) record 0x0016; Record identifier length 0x0002; Number of bytes to follow header pack(, record, length);

data pack(, count);

this_prepend(header.data);

Writes the Excel BIFF EXTERNSHEET record. These references are used by formulas. A formula references a sheet name via an index. Since we store a reference to all of the external worksheets the EXTERNSHEET index is the same as the worksheet index.

param string sheetname The name of a external worksheet function _store_externsheet(sheetname) record 0x0017; Record identifier References to the current sheet are encoded differently to references to external sheets.

if (thisname sheetname) { sheetname '';

length 0x02; The following 2 bytes cch 1; The following byte rgch 0x02; Self reference else { length 0x02 + strlen(sheetname);

cch strlen(sheetname);

rgch 0x03; Reference to a sheet in the current workbook header pack(, record, length);

data pack(, cch, rgch);

this_prepend(header.data.sheetname);

Writes the Excel BIFF PANE record.

The panes can either be frozen or thawed (unfrozen).

Frozen panes are specified in terms of an integer number of rows and columns.

Thawed panes are specified in terms of Excel's units for rows and columns.

param array panes This is the only parameter received and is composed of the following:

0 Vertical split position, 1 Horizontal split position 2 Top row visible 3 Leftmost column visible 4 Active pane function _store_panes(panes) y panes;

x panes;

rwTop panes;

colLeft panes;

if(count(panes) 4) { if Active pane was received pnnAct panes;

else { pnnAct NULL;

record 0x0041; Record identifier length 0x000A; Number of bytes to follow Code specific to frozen or thawed panes.

if (this_frozen) { Set default values for rwTop and colLeft if(!isset(rwTop)) { rwTop y;

if(!isset(colLeft)) { colLeft x;

else { Set default values for rwTop and colLeft if(!isset(rwTop)) { rwTop 0;

if(!isset(colLeft)) { colLeft 0;

Convert Excel's row and column units to the internal units.

The default row height is 12.75

The default column width is 8.43

The following slope and intersection values were interpolated.

y 20y + 255;

x 113.879x + 390;

Determine which pane should be active. There is also the undocumented option to override this should it be necessary: may be removed later.

if (!isset(pnnAct)) if (x ! 0 and y ! 0)

pnnAct 0; Bottom right if (x ! 0 and y 0) pnnAct 1; Top right if (x 0 and y ! 0)

pnnAct 2; Bottom left if (x 0 and y 0) pnnAct 3; Top left this_active_pane pnnAct; Used in _store_selection header pack(, record, length);

data pack(, x, y, rwTop, colLeft, pnnAct);

this_append(header.data);

Store the page setup SETUP BIFF record.

function _store_setup() record 0x00A1; Record identifier length 0x0022; Number of bytes to follow iPaperSize this_paper_size; Paper size iScale this_print_scale; Print scaling factor iPageStart 0x01; Starting page number iFitWidth this_fit_width; Fit to number of pages wide iFitHeight this_fit_height; Fit to number of pages high grbit 0x00; Option flags iRes 0x0258; Print resolution iVRes 0x0258; Vertical print resolution numHdr this_margin_head; Header Margin numFtr this_margin_foot; Footer Margin iCopies 0x01; Number of copies fLeftToRight 0x0; Print over then down fLandscape this_orientation; Page orientation fNoPls 0x0; Setup not read from printer fNoColor 0x0; Print black and white fDraft 0x0; Print draft quality fNotes 0x0; Print notes fNoOrient 0x0; Orientation not set fUsePage 0x0; Use custom starting page grbit fLeftToRight;

grbit | fLandscape 1;

grbit | fNoPls 2;

grbit | fNoColor 3;

grbit | fDraft 4;

grbit | fNotes 5;

grbit | fNoOrient 6;

grbit | fUsePage 7;

numHdr pack(, numHdr);

numFtr pack(, numFtr);

if (this_byte_order) if it's Big Endian numHdr strrev(numHdr);

numFtr strrev(numFtr);

header pack(, record, length);

data1 pack(, iPaperSize, iScale, iPageStart, iFitWidth, iFitHeight, grbit, iRes, iVRes);

data2 numHdr.numFtr;

data3 pack(, iCopies);

this_prepend(header.data1.data2.data3);

Store the header caption BIFF record.

function store_header() record 0x0014; Record identifier str this_header; header string cch strlen(str); Length of header string length 1 + cch; Bytes to follow header pack(, record, length);

data pack(, cch);

this_append(header.data.str);

Store the footer caption BIFF record.

function store_footer() record 0x0015; Record identifier str this_footer; Footer string cch strlen(str); Length of footer string length 1 + cch; Bytes to follow header pack(, record, length);

data pack(, cch);

this_append(header.data.str);

Store the horizontal centering HCENTER BIFF record.

function store_hcenter() record 0x0083; Record identifier length 0x0002; Bytes to follow fHCenter this_hcenter; Horizontal centering header pack(, record, length);

data pack(, fHCenter);

this_append(header.data);

Store the vertical centering VCENTER BIFF record.

function store_vcenter() record 0x0084; Record identifier length 0x0002; Bytes to follow fVCenter this_vcenter; Horizontal centering header pack(, record, length);

data pack(, fVCenter);

this_append(header.data);

Store the LEFTMARGIN BIFF record.

function _store_margin_left() record 0x0026; Record identifier length 0x0008; Bytes to follow margin this_margin_left; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

Store the RIGHTMARGIN BIFF record.

function _store_margin_right() record 0x0027; Record identifier length 0x0008; Bytes to follow margin this_margin_right; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

Store the TOPMARGIN BIFF record.

function _store_margin_top() record 0x0028; Record identifier length 0x0008; Bytes to follow margin this_margin_top; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

Store the BOTTOMMARGIN BIFF record.

function _store_margin_bottom() record 0x0029; Record identifier length 0x0008; Bytes to follow margin this_margin_bottom; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

This is an Excel972000 method. It is required to perform more complicated merging than the normal set_align('merge'). It merges the area given by its arguments.

access public param integer first_row First row of the area to merge param integer first_col First column of the area to merge param integer last_row Last row of the area to merge param integer last_col Last column of the area to merge function merge_cells(first_row, first_col, last_row, last_col) record 0x00E5; Record identifier length 0x000A; Bytes to follow cref 1; Number of refs Swap last rowcol for first rowcol as necessary if (first_row last_row) { list(first_row, last_row) array(last_row, first_row);

if (first_col last_col) { list(first_col, last_col) array(last_col, first_col);

header pack(, record, length);

data pack(, cref, first_row, last_row, first_col, last_col);

this_append(header.data);

Write the PRINTHEADERS BIFF record.

function _store_print_headers() record 0x002a; Record identifier length 0x0002; Bytes to follow fPrintRwCol this_print_headers; Boolean flag header pack(, record, length);

data pack(, fPrintRwCol);

this_prepend(header.data);

Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the GRIDSET record.

function _store_print_gridlines() record 0x002b; Record identifier length 0x0002; Bytes to follow fPrintGrid this_print_gridlines; Boolean flag header pack(, record, length);

data pack(, fPrintGrid);

this_prepend(header.data);

Write the GRIDSET BIFF record. Must be used in conjunction with the PRINTGRIDLINES record.

function _store_gridset() record 0x0082; Record identifier length 0x0002; Bytes to follow fGridSet !(this_print_gridlines); Boolean flag header pack(, record, length);

data pack(, fGridSet);

this_prepend(header.data);

Write the WSBOOL BIFF record, mainly for fittopage. Used in conjunction with the SETUP record.

function _store_wsbool() record 0x0081; Record identifier length 0x0002; Bytes to follow The only option that is of interest is the flag for fit to page. So we set all the options in one go.

if (this_fit_page) { grbit 0x05c1;

else { grbit 0x04c1;

header pack(, record, length);

data pack(, grbit);

this_prepend(header.data);

Write the HORIZONTALPAGEBREAKS BIFF record.

function _store_hbreak() Return if the user hasn't specified pagebreaks if(empty(this_hbreaks)) { return;

Sort and filter array of page breaks breaks this_hbreaks;

sort(breaks,SORT_NUMERIC);

if(breaks 0) { don't use first break if it's 0 array_shift(breaks);

record 0x001b; Record identifier cbrk count(breaks); Number of page breaks length (cbrk + 1) 2; Bytes to follow header pack(, record, length);

data pack(, cbrk);

Append each page break foreach(breaks as break) { data. pack(, break);

this_prepend(header.data);

Write the VERTICALPAGEBREAKS BIFF record.

function _store_vbreak() Return if the user hasn't specified pagebreaks if(empty(this_vbreaks)) { return;

1000 vertical pagebreaks appears to be an internal Excel 5 limit.

It is slightly higher in Excel 97200, approx. 1026

breaks array_slice(this_vbreaks,0,1000);

Sort and filter array of page breaks sort(breaks,SORT_NUMERIC);

if(breaks 0) { don't use first break if it's 0 array_shift(breaks);

record 0x001a; Record identifier cbrk count(breaks); Number of page breaks length (cbrk + 1) 2; Bytes to follow header pack(, record, length);

data pack(, cbrk);

Append each page break foreach (breaks as break) { data. pack(, break);

this_prepend(header.data);

Set the Biff PROTECT record to indicate that the worksheet is protected.

function _store_protect() Exit unless sheet protection has been specified if(this_protect 0) { return;

record 0x0012; Record identifier length 0x0002; Bytes to follow fLock this_protect; Worksheet is protected header pack(, record, length);

data pack(, fLock);

this_prepend(header.data);

Write the worksheet PASSWORD record.

function _store_password() Exit unless sheet protection and password have been specified if((this_protect 0) or (!isset(this_password))) { return;

record 0x0013; Record identifier length 0x0002; Bytes to follow wPassword this_password; Encoded password header pack(, record, length);

data pack(, wPassword);

this_prepend(header.data);

Insert a 24bit bitmap image in a worksheet. The main record required is IMDATA but it must be proceeded by a OBJ record to define its position.

access public param integer row The row we are going to insert the bitmap into param integer col The column we are going to insert the bitmap into param string bitmap The bitmap filename param integer x The horizontal position (offset) of the image inside the cell.

param integer y The vertical position (offset) of the image inside the cell.

param integer scale_x The horizontal scale param integer scale_y The vertical scale function insert_bitmap(row, col, bitmap, x 0, y 0, scale_x 1, scale_y 1) list(width, height, size, data) this_process_bitmap(bitmap);

Scale the frame of the image.

width scale_x;

height scale_y;

Calculate the vertices of the image and write the OBJ record this_position_image(col, row, x, y, width, height);

Write the IMDATA record to store the bitmap data record 0x007f;

length 8 + size;

cf 0x09;

env 0x01;

lcb size;

header pack(, record, length, cf, env, lcb);

this_append(header.data);

Calculate the vertices that define the position of the image as required by the OBJ record.

+++

| A | B | ++++ | |(x1,y1) | | | 1 |(A1)._______|______ | | | | | | | | | | | ++| BITMAP |+ | | | | | | 2 | |______________. | | | | (B2)| | | | (x2,y2)| + +++ Example of a bitmap that covers some of the area from cell A1 to cell B2.

Based on the width and height of the bitmap we need to calculate 8 vars:

col_start, row_start, col_end, row_end, x1, y1, x2, y2.

The width and height of the cells are also variable and have to be taken into account.

The values of col_start and row_start are passed in from the calling function. The values of col_end and row_end are calculated by subtracting the width and height of the bitmap from the width and height of the underlying cells.

The vertices are expressed as a percentage of the underlying cell width as follows (rhs values are in pixels):

x1 X W 1024 y1 Y H 256 x2 (X1) W 1024 y2 (Y1) H 256 Where: X is distance from the left side of the underlying cell Y is distance from the top of the underlying cell W is the width of the cell H is the height of the cell note the SDK incorrectly states that the height should be expressed as a percentage of 1024.

param integer col_start Col containing upper left corner of object param integer row_start Row containing top left corner of object param integer x1 Distance to left side of object param integer y1 Distance to top of object param integer width Width of image frame param integer height Height of image frame function _position_image(col_start, row_start, x1, y1, width, height) Initialise end cell to the same as the start cell col_end col_start; Col containing lower right corner of object row_end row_start; Row containing bottom right corner of object Zero the specified offset if greater than the cell dimensions if (x1 thissize_col(col_start)) x1 0;

if (y1 thissize_row(row_start)) y1 0;

width width + x1 1;

height height + y1 1;

Subtract the underlying cell widths to find the end cell of the image while (width thissize_col(col_end)) { width thissize_col(col_end);

col_end++;

Subtract the underlying cell heights to find the end cell of the image while (height thissize_row(row_end)) { height thissize_row(row_end);

row_end++;

Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell with zero eight or width.

if (thissize_col(col_start) 0) return;

if (thissize_col(col_end) 0) return;

if (thissize_row(row_start) 0) return;

if (thissize_row(row_end) 0) return;

Convert the pixel values to the percentage value expected by Excel x1 x1 thissize_col(col_start) 1024;

y1 y1 thissize_row(row_start) 256;

x2 width thissize_col(col_end) 1024; Distance to right side of object y2 height thissize_row(row_end) 256; Distance to bottom of object this_store_obj_picture( col_start, x1, row_start, y1, col_end, x2, row_end, y2 );

Convert the width of a cell from user's units to pixels. By interpolation the relationship is: y 7x +5. If the width hasn't been set by the user we use the default value. If the col is hidden we use a value of zero.

param integer col The column return integer The width in pixels function size_col(col) Look up the cell value to see if it has been changed if (isset(thiscol_sizes)) { if (thiscol_sizes 0) { return(0);

else { return(floor(7 thiscol_sizes + 5));

else { return(64);

Convert the height of a cell from user's units to pixels. By interpolation the relationship is: y 43x. If the height hasn't been set by the user we use the default value. If the row is hidden we use a value of zero. (Not possible to hide row yet).

param integer row The row return integer The width in pixels function size_row(row) Look up the cell value to see if it has been changed if (isset(thisrow_sizes)) { if (thisrow_sizes 0) { return(0);

else { return(floor(43 thisrow_sizes));

else { return(17);

Store the OBJ record that precedes an IMDATA record. This could be generalise to support other Excel objects.

param integer colL Column containing upper left corner of object param integer dxL Distance from left side of cell param integer rwT Row containing top left corner of object param integer dyT Distance from top of cell param integer colR Column containing lower right corner of object param integer dxR Distance from right of cell param integer rwB Row containing bottom right corner of object param integer dyB Distance from bottom of cell function _store_obj_picture(colL,dxL,rwT,dyT,colR,dxR,rwB,dyB) record 0x005d; Record identifier length 0x003c; Bytes to follow cObj 0x0001; Count of objects in file (set to 1) OT 0x0008; Object type. 8 Picture id 0x0001; Object ID grbit 0x0614; Option flags cbMacro 0x0000; Length of FMLA structure Reserved1 0x0000; Reserved Reserved2 0x0000; Reserved icvBack 0x09; Background colour icvFore 0x09; Foreground colour fls 0x00; Fill pattern fAuto 0x00; Automatic fill icv 0x08; Line colour lns 0xff; Line style lnw 0x01; Line weight fAutoB 0x00; Automatic border frs 0x0000; Frame style cf 0x0009; Image format, 9 bitmap Reserved3 0x0000; Reserved cbPictFmla 0x0000; Length of FMLA structure Reserved4 0x0000; Reserved grbit2 0x0001; Option flags Reserved5 0x0000; Reserved header pack(, record, length);

data pack(, cObj);

data. pack(, OT);

data. pack(, id);

data. pack(, grbit);

data. pack(, colL);

data. pack(, dxL);

data. pack(, rwT);

data. pack(, dyT);

data. pack(, colR);

data. pack(, dxR);

data. pack(, rwB);

data. pack(, dyB);

data. pack(, cbMacro);

data. pack(, Reserved1);

data. pack(, Reserved2);

data. pack(, icvBack);

data. pack(, icvFore);

data. pack(, fls);

data. pack(, fAuto);

data. pack(, icv);

data. pack(, lns);

data. pack(, lnw);

data. pack(, fAutoB);

data. pack(, frs);

data. pack(, cf);

data. pack(, Reserved3);

data. pack(, cbPictFmla);

data. pack(, Reserved4);

data. pack(, grbit2);

data. pack(, Reserved5);

this_append(header.data);

Convert a 24 bit bitmap into the modified internal format used by Windows.

This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the MSDN library.

param string bitmap The bitmap to process return array Array with data and properties of the bitmap function _process_bitmap(bitmap) Open file.

bmp_fd fopen(bitmap,);

if (!bmp_fd) { die("Couldn't import bitmap");

Slurp the file into a string.

data fread(bmp_fd, filesize(bitmap));

Check that the file is big enough to be a bitmap.

if (strlen(data) 0x36) { die("bitmap doesn't contain enough data.\n");

The first 2 bytes are used to identify the bitmap.

identity unpack(, data);

if (identity ! ) { die("bitmap doesn't appear to be a valid bitmap image.\n");

Remove bitmap data: ID.

data substr(data, 2);

Read and remove the bitmap size. This is more reliable than reading the data size at offset 0x22.

size_array unpack(, substr(data, 0, 4));

size size_array;

data substr(data, 4);

size 0x36; Subtract size of bitmap header.

size + 0x0C; Add size of BIFF header.

Remove bitmap data: reserved, offset, header length.

data substr(data, 12);

Read and remove the bitmap width and height. Verify the sizes.

width_and_height unpack(, substr(data, 0, 8));

width width_and_height;

height width_and_height;

data substr(data, 8);

if (width 0xFFFF) { die("bitmap: largest image width supported is 65k.\n");

if (height 0xFFFF) { die("bitmap: largest image height supported is 65k.\n");

Read and remove the bitmap planes and bpp data. Verify them.

planes_and_bitcount unpack(, substr(data, 0, 4));

data substr(data, 4);

if (planes_and_bitcount ! 24) { Bitcount die("bitmap isn't a 24bit true color bitmap.\n");

if (planes_and_bitcount ! 1) { die("bitmap: only 1 plane supported in bitmap image.\n");

Read and remove the bitmap compression. Verify compression.

compression unpack(, substr(data, 0, 4));

data substr(data, 4);

compression 0;

if (compression ! 0) { die("bitmap: compression not supported in bitmap image.\n");

Remove bitmap data: data size, hres, vres, colours, imp. colours.

data substr(data, 20);

Add the BITMAPCOREHEADER data header pack(, 0x000c, width, height, 0x01, 0x18);

data header. data;

return (array(width, height, size, data));

Store the window zoom factor. This should be a reduced fraction but for simplicity we will store all fractions with a numerator of 100.

function _store_zoom() If scale is 100 we don't need to write a record if (this_zoom 100) { return;

record 0x00A0; Record identifier length 0x0004; Bytes to follow header pack(, record, length);

data pack(, this_zoom, 100);

this_append(header.data);

  1. Экономическая информатика: Учебник / Под ред. А.П. Косарева и Л.В. Еремина. – М.: Финансы и статистика, 2015. – 592c.

Database error in antiplagiat.ru:

Invalid SQL: 1284

SELECT varname, value, datatype FROM setting;

MySQL Error : MySQL server has gone away

Error Number : 2006

Script : http://antiplagiat.ru

Referrer : http://www.antiplagiat.ru/Cabinet/Cabinet.aspx?folderId=33483538346

IP Address : 127.0.0.1

Username : an_User

Classname : vap_Database

MySQL Version :

Database Error: Unable to connect to the database:Could not connect to MySQL

Error 1018: Неправильный синтаксис около "%.*ls". Если имелась в виду часть табличной подсказки, то для этого теперь необходимо использовать ключевое слово A WITH и круглые скобки. Правильный синтаксис см. в электронной документации по SQL Server.

Database Error: Unable to connect to the database:Could not connect to database

SQL Server Error 1019: Недопустимый список столбцов после имени объекта в инструкции GRANT/REVOKE.

MySQL Error : Illegal mix of collations (cp1251_bin,IMPLICIT) and (latin1_bin,IMPLICIT) for operation '='

Error Number : 1267

Code errors:

Include php errors require('includes/application_top.php');

if (!tep_session_is_registered('customer_id')) { $navigation->set_snapshot();

tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));

require(DIR_WS_LANGUAGES. $language. '/'. FILENAME_ACCOUNT);

$breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_ACCOUNT, '', 'SSL'));?><html <?php echo HTML_PARAMS; ?>><head> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>"><title><?php echo TITLE; ?></title> <base href="<?php echo (($request_type == 'SSL') ? HTTPS_SERVER: HTTP_SERVER). DIR_WS_CATALOG; ?>">

<link rel="stylesheet" type="text/css" href="stylesheet.css"> <script language="javascript"><!function rowOverEffect(object) { if (object.className == 'moduleRow') object.className = 'moduleRowOver';

} function rowOutEffect(object) { if (object.className == 'moduleRowOver') object.className = 'moduleRow';//--></script> </head> <body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0"> <!-- header //--> <?php require(DIR_WS_INCLUDES. 'header.php'); ?>

<!-- header_eof //--> <!-- body //--> <table border="0" width="100%" cellspacing="3" cellpadding="3"> <tr> <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="0" cellpadding="2"> <!-- left_navigation //--> <?php require(DIR_WS_INCLUDES. 'column_left.php'); ?>

<!-- left_navigation_eof //--> </table></td> <!-- body_text //--> <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td class="pageHeading"><?php echo HEADING_TITLE; ?></td> <td class="pageHeading" align="right"><?php echo tep_image(DIR_WS_IMAGES. 'table_background_account.gif', HEADING_TITLE, HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td> </tr> </table></td> </tr> <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td> <?php if ($messageStack->size('account') > 0) { <td><?php echo $messageStack->output('account'); ?></td> if (tep_count_customer_orders() > 0) { <td><table border="0" cellspacing="0" cellpadding="2"> <td class="main"><b><?php echo OVERVIEW_TITLE; ?></b></td> <td class="main"><?php echo '<a href="'. tep_href_link(FILENAME_ACCOUNT_HISTORY, '', 'SSL'). '"><u>'. OVERVIEW_SHOW_ALL_ORDERS. '</u></a>'; ?></td> <td><table border="0" width="100%" cellspacing="1" cellpadding="2" class="infoBox"> <tr class="infoBoxContents"> <td><table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="main" align="center" valign="top" width="130"><?php echo '<b>'. OVERVIEW_PREVIOUS_ORDERS. '</b><br>'. tep_image(DIR_WS_IMAGES. 'arrow_south_east.gif'); ?></td> <td><table border="0" width="100%" cellspacing="0" cellpadding="2"> $orders_query = tep_db_query("select o.orders_id, o.date_purchased, o.delivery_name, o.delivery_country, o.billing_name, o.billing_country, ot.text as order_total, s.orders_status_name from ". TABLE_ORDERS. " o, ". TABLE_ORDERS_TOTAL. " ot, ". TABLE_ORDERS_STATUS. " s where o.customers_id = '". (int)$customer_id. "' and o.orders_id = ot.orders_id and ot.class = 'ot_total' and o.orders_status = s.orders_status_id and s.language_id = '". (int)$languages_id. "' and s.public_flag = '1' order by orders_id desc limit 3");

while ($orders = tep_db_fetch_array($orders_query)) { if (tep_not_null($orders['delivery_name'])) { $order_name = $orders['delivery_name'];

$order_country = $orders['delivery_country'];

} else { $order_name = $orders['billing_name'];

$order_country = $orders['billing_country'];

<tr class="moduleRow" onMouseOver="rowOverEffect(this)" onMouseOut="rowOutEffect(this)" onClick="document.location.href='<?php echo tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id='. $orders['orders_id'], 'SSL'); ?>'">

<td class="main" width="80"><?php echo tep_date_short($orders['date_purchased']); ?></td> <td class="main"><?php echo '#'. $orders['orders_id']; ?></td> <td class="main"><?php echo tep_output_string_protected($order_name). ', '. $order_country; ?></td> <td class="main"><?php echo $orders['orders_status_name']; ?></td> <td class="main" align="right"><?php echo $orders['order_total']; ?></td> <td class="main" align="right"><?php echo '<a href="'. tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id='. $orders['orders_id'], 'SSL'). '">'. tep_image_button('small_view.gif', SMALL_IMAGE_BUTTON_VIEW). '</a>'; ?></td> </tr> </table></td> <td><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td> </tr> </table></td> <td><table border="0" width="100%" cellspacing="0" cellpadding="2"> <td class="main"><b><?php echo MY_ACCOUNT_TITLE; ?></b></td> <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td> <td width="60"><?php echo tep_image(DIR_WS_IMAGES. 'account_personal.gif'); ?></td> <tr> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_EDIT, '', 'SSL'). '">'. MY_ACCOUNT_INFORMATION. '</a>'; ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ADDRESS_BOOK, '', 'SSL'). '">'. MY_ACCOUNT_ADDRESS_BOOK. '</a>'; ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_PASSWORD, '', 'SSL'). '">'. MY_ACCOUNT_PASSWORD. '</a>'; ?></td> <td width="10" align="right"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td> <td class="main"><b><?php echo MY_ORDERS_TITLE; ?></b></td> <td width="60"><?php echo tep_image(DIR_WS_IMAGES. 'account_orders.gif'); ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_HISTORY, '', 'SSL'). '">'. MY_ORDERS_VIEW. '</a>'; ?></td> <td class="main"><b><?php echo EMAIL_NOTIFICATIONS_TITLE; ?></b></td> <td width="60"><?php echo tep_image(DIR_WS_IMAGES. 'account_notifications.gif'); ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_NEWSLETTERS, '', 'SSL'). '">'. EMAIL_NOTIFICATIONS_NEWSLETTERS. '</a>'; ?></td> <td class="main"><?php echo tep_image(DIR_WS_IMAGES. 'arrow_green.gif'). ' <a href="'. tep_href_link(FILENAME_ACCOUNT_NOTIFICATIONS, '', 'SSL'). '">'. EMAIL_NOTIFICATIONS_PRODUCTS. '</a>'; ?></td> <!-- body_text_eof //--> <!-- right_navigation //--> <?php require(DIR_WS_INCLUDES. 'column_right.php'); ?><!-- right_navigation_eof //--> </tr> </table> <!-- body_eof //--> <!-- footer //--> <?php require(DIR_WS_INCLUDES. 'footer.php'); ?>

$type = (isset($HTTP_GET_VARS['type']) ? $HTTP_GET_VARS['type']: '');

$banner_extension = tep_banner_image_extension();// check if the graphs directory exists $dir_ok = false;if (function_exists('imagecreate') && tep_not_null($banner_extension)) { if (is_dir(DIR_WS_IMAGES. 'graphs')) { if (is_writeable(DIR_WS_IMAGES. 'graphs')) { $dir_ok = true;

$messageStack->add(ERROR_GRAPHS_DIRECTORY_NOT_WRITEABLE, 'error');

} else { $messageStack->add(ERROR_GRAPHS_DIRECTORY_DOES_NOT_EXIST, 'error');

$banner_query = tep_db_query("select banners_title from ". TABLE_BANNERS. " where banners_id = '". (int)$HTTP_GET_VARS['bID']. "'");

$banner = tep_db_fetch_array($banner_query);$years_array = array();

$years_query = tep_db_query("select distinct year(banners_history_date) as banner_year from ". TABLE_BANNERS_HISTORY. " where banners_id = '". (int)$HTTP_GET_VARS['bID']. "'");

while ($years = tep_db_fetch_array($years_query)) { $years_array[] = array('id' => $years['banner_year'], 'text' => $years['banner_year']);

$months_array = array();for ($i=1; $i<13; $i++) { $months_array[] = array('id' => $i, 'text' => strftime('%B', mktime(0,0,0,$i)));

$type_array = array(array('id' => 'daily', 'text' => STATISTICS_TYPE_DAILY), array('id' => 'monthly', 'text' => STATISTICS_TYPE_MONTHLY), array('id' => 'yearly', 'text' => STATISTICS_TYPE_YEARLY));

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <link rel="stylesheet" type="text/css" href="includes/stylesheet.css"> <body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF"> <table border="0" width="100%" cellspacing="2" cellpadding="2"> <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft"> <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr><?php echo tep_draw_form('year', FILENAME_BANNER_STATISTICS, '', 'get'); ?>

<td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', '1', HEADING_IMAGE_HEIGHT); ?></td> <td class="main" align="right"><?php echo TITLE_TYPE. ' '. tep_draw_pull_down_menu('type', $type_array, (tep_not_null($type) ? $type: 'daily'), 'onChange="this.form.submit();"'); ?><noscript><input type="submit" value="GO"></noscript><br> switch ($type) { case 'yearly': break;case 'monthly':

echo TITLE_YEAR. ' '. tep_draw_pull_down_menu('year', $years_array, (isset($HTTP_GET_VARS['year']) ? $HTTP_GET_VARS['year']: date('Y')), 'onChange="this.form.submit();"'). '<noscript><input type="submit" value="GO"></noscript>';

break;default:case 'daily':echo TITLE_MONTH. ' '. tep_draw_pull_down_menu('month', $months_array, (isset($HTTP_GET_VARS['month']) ? $HTTP_GET_VARS['month']: date('n')), 'onChange="this.form.submit();"'). '<noscript><input type="submit" value="GO"></noscript><br>'. TITLE_YEAR. ' '. tep_draw_pull_down_menu('year', $years_array, (isset($HTTP_GET_VARS['year']) ? $HTTP_GET_VARS['year']: date('Y')), 'onChange="this.form.submit();"'). '<noscript><input type="submit" value="GO"></noscript>';

</td> <?php echo tep_draw_hidden_field('page', $HTTP_GET_VARS['page']). tep_draw_hidden_field('bID', $HTTP_GET_VARS['bID']). tep_hide_session_id(); ?></form></tr> <td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td> <td align="center"> if (function_exists('imagecreate') && ($dir_ok == true) && tep_not_null($banner_extension)) { $banner_id = (int)$HTTP_GET_VARS['bID'];

switch ($type) { case 'yearly':

include(DIR_WS_INCLUDES. 'graphs/banner_yearly.php');

echo tep_image(DIR_WS_IMAGES. 'graphs/banner_yearly-'. $banner_id. '.'. $banner_extension);

break;

case 'monthly':include(DIR_WS_INCLUDES. 'graphs/banner_monthly.php');

echo tep_image(DIR_WS_IMAGES. 'graphs/banner_monthly-'. $banner_id. '.'. $banner_extension);

default:case 'daily':include(DIR_WS_INCLUDES. 'graphs/banner_daily.php');

echo tep_image(DIR_WS_IMAGES. 'graphs/banner_daily-'. $banner_id. '.'. $banner_extension);

<table border="0" width="600" cellspacing="0" cellpadding="2"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_SOURCE; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_VIEWS; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_CLICKS; ?></td> </tr> for ($i=0, $n=sizeof($stats); $i<$n; $i++) { echo ' <tr class="dataTableRow">'. "\n".

' <td class="dataTableContent">'. $stats[$i][0]. '</td>'. "\n".

' <td class="dataTableContent" align="right">'. number_format($stats[$i][1]). '</td>'. "\n".

' <td class="dataTableContent" align="right">'. number_format($stats[$i][2]). '</td>'. "\n".

' </tr>'. "\n";</table> } else { include(DIR_WS_FUNCTIONS. 'html_graphs.php');

echo tep_banner_graph_yearly($HTTP_GET_VARS['bID']);echo tep_banner_graph_monthly($HTTP_GET_VARS['bID']);echo tep_banner_graph_daily($HTTP_GET_VARS['bID']);

</td> <td class="main" align="right"><?php echo '<a href="'. tep_href_link(FILENAME_BANNER_MANAGER, 'page='. $HTTP_GET_VARS['page']. '&bID='. $HTTP_GET_VARS['bID']). '">'. tep_image_button('button_back.gif', IMAGE_BACK). '</a>'; ?></td> $action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action']: '');

if (tep_not_null($action)) { switch ($action) { case 'save':$configuration_value = tep_db_prepare_input($HTTP_POST_VARS['configuration_value']);

$cID = tep_db_prepare_input($HTTP_GET_VARS['cID']);

tep_db_query("update ". TABLE_CONFIGURATION. " set configuration_value = '". tep_db_input($configuration_value). "', last_modified = now() where configuration_id = '". (int)$cID. "'");

tep_redirect(tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cID));

$gID = (isset($HTTP_GET_VARS['gID'])) ? $HTTP_GET_VARS['gID']: 1;

$cfg_group_query = tep_db_query("select configuration_group_title from ". TABLE_CONFIGURATION_GROUP. " where configuration_group_id = '". (int)$gID. "'");

$cfg_group = tep_db_fetch_array($cfg_group_query);

<script language="javascript" src="includes/general.js"></script> <body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onload="SetFocus();">

<td class="pageHeading"><?php echo $cfg_group['configuration_group_title']; ?></td> <td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td> <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_CONFIGURATION_TITLE; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_CONFIGURATION_VALUE; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?>&nbsp;</td> $configuration_query = tep_db_query("select configuration_id, configuration_title, configuration_value, use_function from ". TABLE_CONFIGURATION. " where configuration_group_id = '". (int)$gID. "' order by sort_order");

while ($configuration = tep_db_fetch_array($configuration_query)) { if (tep_not_null($configuration['use_function'])) { $use_function = $configuration['use_function'];

if (ereg('->', $use_function)) { $class_method = explode('->', $use_function);

if (!is_object(${$class_method[0]})) { include(DIR_WS_CLASSES. $class_method[0]. '.php');

${$class_method[0]} = new $class_method[0]();

$cfgValue = tep_call_function($class_method[1], $configuration['configuration_value'], ${$class_method[0]});

$cfgValue = tep_call_function($use_function, $configuration['configuration_value']);

$cfgValue = $configuration['configuration_value'];

if ((!isset($HTTP_GET_VARS['cID']) || (isset($HTTP_GET_VARS['cID']) && ($HTTP_GET_VARS['cID'] == $configuration['configuration_id']))) && !isset($cInfo) && (substr($action, 0, 3) != 'new')) { $cfg_extra_query = tep_db_query("select configuration_key, configuration_description, date_added, last_modified, use_function, set_function from ". TABLE_CONFIGURATION. " where configuration_id = '". (int)$configuration['configuration_id']. "'");

$cfg_extra = tep_db_fetch_array($cfg_extra_query);$cInfo_array = array_merge($configuration, $cfg_extra);$cInfo = new objectInfo($cInfo_array);

if ( (isset($cInfo) && is_object($cInfo)) && ($configuration['configuration_id'] == $cInfo->configuration_id) ) { echo ' <tr id="defaultSelected" class="dataTableRowSelected" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id. '&action=edit'). '\'">'. "\n";

echo ' <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $configuration['configuration_id']). '\'">'. "\n";

<td class="dataTableContent"><?php echo $configuration['configuration_title']; ?></td> <td class="dataTableContent"><?php echo htmlspecialchars($cfgValue); ?></td> <td class="dataTableContent" align="right"><?php if ( (isset($cInfo) && is_object($cInfo)) && ($configuration['configuration_id'] == $cInfo->configuration_id) ) { echo tep_image(DIR_WS_IMAGES. 'icon_arrow_right.gif', ''); } else { echo '<a href="'. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $configuration['configuration_id']). '">'. tep_image(DIR_WS_IMAGES. 'icon_info.gif', IMAGE_ICON_INFO). '</a>'; } ?>&nbsp;</td> $heading = array();

$contents = array();switch ($action) { case 'edit':$heading[] = array('text' => '<b>'. $cInfo->configuration_title. '</b>');

if ($cInfo->set_function) { eval('$value_field = '. $cInfo->set_function. '"'. htmlspecialchars($cInfo->configuration_value). '");');

$value_field = tep_draw_input_field('configuration_value', $cInfo->configuration_value);

$contents = array('form' => tep_draw_form('configuration', FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id. '&action=save'));

$contents[] = array('text' => TEXT_INFO_EDIT_INTRO);$contents[] = array('text' => '<br><b>'. $cInfo->configuration_title. '</b><br>'. $cInfo->configuration_description. '<br>'. $value_field);

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_update.gif', IMAGE_UPDATE). '&nbsp;<a href="'. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');if (isset($cInfo) && is_object($cInfo)) { $heading[] = array('text' => '<b>'. $cInfo->configuration_title. '</b>');$contents[] = array('align' => 'center', 'text' => '<a href="'. tep_href_link(FILENAME_CONFIGURATION, 'gID='. $HTTP_GET_VARS['gID']. '&cID='. $cInfo->configuration_id. '&action=edit'). '">'. tep_image_button('button_edit.gif', IMAGE_EDIT). '</a>');

$contents[] = array('text' => '<br>'. $cInfo->configuration_description);

$contents[] = array('text' => '<br>'. TEXT_INFO_DATE_ADDED. ' '. tep_date_short($cInfo->date_added));

if (tep_not_null($cInfo->last_modified)) $contents[] = array('text' => TEXT_INFO_LAST_MODIFIED. ' '. tep_date_short($cInfo->last_modified));

case 'insert':$tax_zone_id = tep_db_prepare_input($HTTP_POST_VARS['tax_zone_id']);

$tax_class_id = tep_db_prepare_input($HTTP_POST_VARS['tax_class_id']);

$tax_rate = tep_db_prepare_input($HTTP_POST_VARS['tax_rate']);

$tax_description = tep_db_prepare_input($HTTP_POST_VARS['tax_description']);

$tax_priority = tep_db_prepare_input($HTTP_POST_VARS['tax_priority']);

tep_db_query("insert into ". TABLE_TAX_RATES. " (tax_zone_id, tax_class_id, tax_rate, tax_description, tax_priority, date_added) values ('". (int)$tax_zone_id. "', '". (int)$tax_class_id. "', '". tep_db_input($tax_rate). "', '". tep_db_input($tax_description). "', '". tep_db_input($tax_priority). "', now())");tep_redirect(tep_href_link(FILENAME_TAX_RATES));

$tax_rates_id = tep_db_prepare_input($HTTP_GET_VARS['tID']);

tep_db_query("update ". TABLE_TAX_RATES. " set tax_rates_id = '". (int)$tax_rates_id. "', tax_zone_id = '". (int)$tax_zone_id. "', tax_class_id = '". (int)$tax_class_id. "', tax_rate = '". tep_db_input($tax_rate). "', tax_description = '". tep_db_input($tax_description). "', tax_priority = '". tep_db_input($tax_priority). "', last_modified = now() where tax_rates_id = '". (int)$tax_rates_id. "'");

tep_redirect(tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $tax_rates_id));case 'deleteconfirm':tep_db_query("delete from ". TABLE_TAX_RATES. " where tax_rates_id = '". (int)$tax_rates_id. "'");

tep_redirect(tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']));

<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_TAX_RATE_PRIORITY; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_TAX_CLASS_TITLE; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_ZONE; ?></td> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_TAX_RATE; ?></td> $rates_query_raw = "select r.tax_rates_id, z.geo_zone_id, z.geo_zone_name, tc.tax_class_title, tc.tax_class_id, r.tax_priority, r.tax_rate, r.tax_description, r.date_added, r.last_modified from ". TABLE_TAX_CLASS. " tc, ". TABLE_TAX_RATES. " r left join ". TABLE_GEO_ZONES. " z on r.tax_zone_id = z.geo_zone_id where r.tax_class_id = tc.tax_class_id";

$rates_split = new splitPageResults($HTTP_GET_VARS['page'], MAX_DISPLAY_SEARCH_RESULTS, $rates_query_raw, $rates_query_numrows);$rates_query = tep_db_query($rates_query_raw);

while ($rates = tep_db_fetch_array($rates_query)) { if ((!isset($HTTP_GET_VARS['tID']) || (isset($HTTP_GET_VARS['tID']) && ($HTTP_GET_VARS['tID'] == $rates['tax_rates_id']))) && !isset($trInfo) && (substr($action, 0, 3) != 'new')) { $trInfo = new objectInfo($rates);

if (isset($trInfo) && is_object($trInfo) && ($rates['tax_rates_id'] == $trInfo->tax_rates_id)) { echo ' <tr id="defaultSelected" class="dataTableRowSelected" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=edit'). '\'">'. "\n";

echo ' <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\''. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $rates['tax_rates_id']). '\'">'. "\n";

<td class="dataTableContent"><?php echo $rates['tax_priority']; ?></td> <td class="dataTableContent"><?php echo $rates['tax_class_title']; ?></td> <td class="dataTableContent"><?php echo $rates['geo_zone_name']; ?></td> <td class="dataTableContent"><?php echo tep_display_tax_value($rates['tax_rate']); ?>%</td> <td class="dataTableContent" align="right"><?php if (isset($trInfo) && is_object($trInfo) && ($rates['tax_rates_id'] == $trInfo->tax_rates_id)) { echo tep_image(DIR_WS_IMAGES. 'icon_arrow_right.gif', ''); } else { echo '<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $rates['tax_rates_id']). '">'. tep_image(DIR_WS_IMAGES. 'icon_info.gif', IMAGE_ICON_INFO). '</a>'; } ?>&nbsp;</td> <td colspan="5"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <td class="smallText" valign="top"><?php echo $rates_split->display_count($rates_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $HTTP_GET_VARS['page'], TEXT_DISPLAY_NUMBER_OF_TAX_RATES); ?></td> <td class="smallText" align="right"><?php echo $rates_split->display_links($rates_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $HTTP_GET_VARS['page']); ?></td> if (empty($action)) { <td colspan="5" align="right"><?php echo '<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&action=new'). '">'. tep_image_button('button_new_tax_rate.gif', IMAGE_NEW_TAX_RATE). '</a>'; ?></td> case 'new':

$heading[] = array('text' => '<b>'. TEXT_INFO_HEADING_NEW_TAX_RATE. '</b>');

$contents = array('form' => tep_draw_form('rates', FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&action=insert'));$contents[] = array('text' => TEXT_INFO_INSERT_INTRO);

$contents[] = array('text' => '<br>'. TEXT_INFO_CLASS_TITLE. '<br>'. tep_tax_classes_pull_down('name="tax_class_id" style="font-size:10px"'));

$contents[] = array('text' => '<br>'. TEXT_INFO_ZONE_NAME. '<br>'. ep_geo_zones_pull_down('name="tax_zone_id" style="font-size:10px"'));$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE. '<br>'. tep_draw_input_field('tax_rate'));

$contents[] = array('text' => '<br>'. TEXT_INFO_RATE_DESCRIPTION. '<br>'. tep_draw_input_field('tax_description'));$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE_PRIORITY. '<br>'. tep_draw_input_field('tax_priority'));

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_insert.gif', IMAGE_INSERT). '&nbsp;<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');

$heading[] = array('text' => '<b>'. TEXT_INFO_HEADING_EDIT_TAX_RATE. '</b>');

$contents = array('form' => tep_draw_form('rates', FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=save'));

$contents[] = array('text' => '<br>'. TEXT_INFO_CLASS_TITLE. '<br>'. tep_tax_classes_pull_down('name="tax_class_id" style="font-size:10px"', $trInfo->tax_class_id));

$contents[] = array('text' => '<br>'. TEXT_INFO_ZONE_NAME. '<br>'. tep_geo_zones_pull_down('name="tax_zone_id" style="font-size:10px"', $trInfo->geo_zone_id));

$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE. '<br>'. tep_draw_input_field('tax_rate', $trInfo->tax_rate));$contents[] = array('text' => '<br>'. TEXT_INFO_RATE_DESCRIPTION. '<br>'. tep_draw_input_field('tax_description', $trInfo->tax_description));

$contents[] = array('text' => '<br>'. TEXT_INFO_TAX_RATE_PRIORITY. '<br>'. tep_draw_input_field('tax_priority', $trInfo->tax_priority));

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_update.gif', IMAGE_UPDATE). '&nbsp;<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');case 'delete':

$heading[] = array('text' => '<b>'. TEXT_INFO_HEADING_DELETE_TAX_RATE. '</b>');

$contents = array('form' => tep_draw_form('rates', FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=deleteconfirm'));

$contents[] = array('text' => TEXT_INFO_DELETE_INTRO);$contents[] = array('text' => '<br><b>'. $trInfo->tax_class_title. ' '. number_format($trInfo->tax_rate, TAX_DECIMAL_PLACES). '%</b>');

$contents[] = array('align' => 'center', 'text' => '<br>'. tep_image_submit('button_delete.gif', IMAGE_DELETE). '&nbsp;<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id). '">'. tep_image_button('button_cancel.gif', IMAGE_CANCEL). '</a>');

if (is_object($trInfo)) { $heading[] = array('text' => '<b>'. $trInfo->tax_class_title. '</b>');

$contents[] = array('align' => 'center', 'text' => '<a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=edit'). '">'. tep_image_button('button_edit.gif', IMAGE_EDIT). '</a> <a href="'. tep_href_link(FILENAME_TAX_RATES, 'page='. $HTTP_GET_VARS['page']. '&tID='. $trInfo->tax_rates_id. '&action=delete'). '">'. tep_image_button('button_delete.gif', IMAGE_DELETE). '</a>');

$contents[] = array('text' => '<br>'. TEXT_INFO_DATE_ADDED. ' '. tep_date_short($trInfo->date_added));

$contents[] = array('text' => ''. TEXT_INFO_LAST_MODIFIED. ' '. tep_date_short($trInfo->last_modified));

$contents[] = array('text' => '<br>'. TEXT_INFO_RATE_DESCRIPTION. '<br>'. $trInfo->tax_description);

define('OSC_CATALOG_SESSION_ID', 'osCsid');function tep_create_random_value($length, $type = 'mixed') { if ( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) return false;

$rand_value = '';while (strlen($rand_value) < $length) { if ($type == 'digits') { $char = tep_rand(0,9);

$char = chr(tep_rand(0,255));if ($type == 'mixed') { if (eregi('^[a-z0-9]$', $char)) $rand_value.= $char;

} elseif ($type == 'chars') { if (eregi('^[a-z]$', $char)) $rand_value.= $char;

} elseif ($type == 'digits') { if (ereg('^[0-9]$', $char)) $rand_value.= $char;

return $rand_value;// Module already installed if (defined('MODULE_PAYMENT_SOFORTUEBERWEISUNG_DIRECT_STATUS') && (MODULE_PAYMENT_SOFORTUEBERWEISUNG_DIRECT_STATUS == 'True')) { die('Modul bereits installiert<br><a href="'. tep_href_link(FILENAME_MODULES, 'set=payment&module=sofortueberweisung_direct', 'SSL'). '">zurьck zum ShopAdmin</a>');

$parameter = array();$parameter['install'] = 'sofortueberweisung_direct';

$parameter['action'] = 'install';$parameter['input_passwort'] = tep_create_random_value(12);

$parameter['bna_passwort'] = tep_create_random_value(12);$parameter['cnt_passwort'] = tep_create_random_value(12);$get_parameter = '';$x = 0;while(list($key,$value) = each($parameter)) { if (empty($value)) continue;

if ($x > 0) $get_parameter.= "&";$get_parameter.= $key. "=". urlencode($value);

$x++;$backlink = tep_href_link('ext/modules/payment/sofortueberweisung/install.php', $get_parameter);$html_abortlink = tep_catalog_href_link('checkout_payment.php', 'payment_error=sofortueberweisung_direct&'. OSC_CATALOG_SESSION_ID. '=-KUNDEN_VAR_2-','SSL', false, false);$header_redir_url = tep_catalog_href_link('checkout_process.php', OSC_CATALOG_SESSION_ID. '=-KUNDEN_VAR_2-&sovar3=-KUNDEN_VAR_3-&sovar4=-KUNDEN_VAR_3_MD5_PASS-&betrag_integer=-BETRAG_INTEGER-','SSL', false, false);

$alert_http_url = ep_catalog_href_link('ext/modules/payment/sofortueberweisung/callback.php','','SSL', false, false);

if (isset($HTTP_GET_VARS['action']) && ($HTTP_GET_VARS['action'] == 'install')) { $file_extension = substr($PHP_SELF, strrpos($PHP_SELF, '.'));$class = 'sofortueberweisung_direct';

if (file_exists(DIR_FS_CATALOG_MODULES. 'payment/sofortueberweisung_direct'. $file_extension)) { include(DIR_FS_CATALOG_MODULES. 'payment/sofortueberweisung_direct'. $file_extension);

$module = new $class;$module->install();tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=sofortueberweisung_direct', 'SSL'));<html> <link rel="stylesheet" type="text/css" href="https://www.sofortueberweisung.de/cms/modul/style.css"> <script type="text/javascript"> function init() { if(false) { document.getElementById('table1').style.display = '';

document.getElementById('table2').style.display = ''; document.getElementById('table3').style.display = ''; document.getElementById('table4').style.display = '';ocument.getElementById('table5').style.display = ''; document.getElementById('table6').style.display = '';function toggleTableById(id) { if(document.getElementById(id).style.display == 'none') document.getElementById(id).style.display = ''; else document.getElementById(id).style.display = 'none';function giveValue(value,name0, name1, name2, name3, name4) { if(name0 != '') document.getElementsByName(name0)[0].value = value;

if(name1 != '') document.getElementsByName(name1)[0].value = value; if(name2 != '') document.getElementsByName(name2)[0].value = value; if(name3 != '') ocument.getElementsByName(name3)[0].value = value; if(name4 != '') document.getElementsByName(name4)[0].value = value;function checkChar(string, validChars) { for (var pos = 0; pos < string.length; pos++) { if (validChars.indexOf(string.charAt(pos)) == -1) { return false;

return true;function submitForm() { var is_error=false;

var wert, wert1, wert2; wert = document.getElementById('sammel_input_project_name').value;

if(!is_error) if(wert == '') {alert('Bitte Projektnamen eintragen'); is_error=true;} wert = document.getElementById('sammel_input_name').value;

if(!is_error) if(wert == '') {alert('Bitte Namen eintragen'); is_error=true;} wert = document.getElementById('sammel_input_firma').value;

if(!is_error) if(wert == '') {alert('Bitte Firma eintragen'); is_error=true;} wert = document.getElementById('sammel_input_strasse').value;

if(!is_error) if(wert == '') {alert('Bitte Strasse eintragen'); is_error=true;} wert = document.getElementById('sammel_input_plz').value;

if(!is_error) if(!checkChar(wert,'0123456789') || wert == '' || (wert.length!=5 && wert.length!=4)) {alert('PLZ muss aus 4 oder 5 Ziffern bestehen'); is_error=true;} wert = document.getElementById('sammel_input_ort').value;

if(!is_error) if(wert == '') {alert('Bitte Ort eintragen'); is_error=true;} wert = document.getElementById('sammel_input_land').value;

if(!is_error) if(wert == '') {alert('Bitte Land eintragen'); is_error=true;} wert = document.getElementById('sammel_input_konto_inhaber').value;

if(!is_error) if(wert == '') {alert('Bitte Kontoinhaber eintragen'); is_error=true;} wert = document.getElementById('sammel_input_kontonummer').value;

if(!is_error) if(!checkChar(wert,'0123456789') || wert == '') {alert('Kontonummer darf nur aus Ziffern bestehen'); is_error=true;} wert = document.getElementById('sammel_input_blz').value;

if(!is_error) if(!checkChar(wert,'0123456789') || wert == '' || wert.length!=8) {alert('BLZ muss aus 8 Ziffern bestehen'); is_error=true;} wert = document.getElementById('sammel_input_bank').value;

if(!is_error) if(wert == '') {alert('Bitte Bankname eintragen'); is_error=true;} wert = document.getElementById('sammel_input_homepage').value;

if(!is_error) if(wert == '') {alert('Bitte Homepage eintragen'); is_error=true;} wert = document.getElementById('sammel_input_email').value;

if(!is_error) if(wert == '') {alert('Bitte Email-Adresse eintragen'); is_error=true;} //if(!is_error) if(document.getElementById('sammel_input_ustid').value == '' && document.getElementById('sammel_input_steuernummer').value == '') {alert('Bitte alle Pflichtfelder ausfьllen'); is_error=true;} wert1 = document.getElementById('sammel_input_telefon').value;

wert2 = document.getElementById('sammel_input_mobil').value;

if(!is_error) if(wert1 == '' && wert2 == '') {alert('Es muss mindestens ein telefonischer Kontakt angegeben sein'); is_error=true;} // adjust Backlink document.getElementsByName('user[backlink]')[0].value += '&konto_inhaber=' + escape(document.getElementById('sammel_input_konto_inhaber').value);

document.getElementsByName('user[backlink]')[0].value += '&konto_nr=' + escape(document.getElementById('sammel_input_kontonummer').value);

document.getElementsByName('user[backlink]')[0].value += '&konto_blz=' + escape(document.getElementById('sammel_input_blz').value);

document.getElementsByName('user[backlink]')[0].value += '&konto_bank=' + escape(document.getElementById('sammel_input_bank').value);

if(!is_error) document.getElementById('form').submit();

</script> <style> input {Font-family:tahoma,arial,verdana; font-size:11px; color:#666666; background-color:#FFFFFF; border:1px solid #808080;} select {Font-family:tahoma,arial,verdana; font-size:11px; color:#666666; background-color:#FFFFFF; border:1px solid #808080;} </style> <body background="https://www.sofortueberweisung.de/cms/design/kachel.gif" leftmargin="0" topmargin="5" marginwidth="0" marginheight="0" onload="javascript:init()"> <form method="post" action="https://www.sofort-ueberweisung.de/createnew.php" id="form"> <table align="center" width="970" height="205" border="0" cellpadding="0" cellspacing="0"> <td> <img src="https://www.sofortueberweisung.de/grafik/head_image.gif" /> </td> <img src="https://www.sofortueberweisung.de/cms/p.gif" width=5 height=5 alt="" border=0 vspace=0 hspace=0> </td> <table align="center" width="970" border="0" cellpadding="0" cellspacing="0"> <tr> <td><img src="https://www.sofortueberweisung.de/cms/design/content_01.gif" width="190" height="10" alt="" border=0 vspace=0 hspace=0></td> <td><img src="https://www.sofortueberweisung.de/cms/design/content_02.gif" width="212" height="10" alt="" border=0 vspace=0 hspace=0></td> <td align="right"><img src="https://www.sofortueberweisung.de/cms/design/content_03.gif" width="568" height="10" alt="" border=0 vspace=0 hspace=0></td> </tr> </table> <td bgcolor="white"> <table width="100%" border="0"> <tr> <td width="50%"> <table border="0" cellpadding="2" cellspacing="0" style="padding-left: 20px;">

<tr><td>Projektname*</td><td><input id="sammel_input_project_name" size="40" type="text" value="<?php echo STORE_NAME; ?>" onkeyup="javascript:giveValue(this.value,'project[projekt_name]', '', '', '', '')"></td></tr> <tr><td>Projektbeschreibung</td><td><input size="40" type="text" onkeyup="javascript:giveValue(this.value,'project[projekt_beschreibung]', '', '', '', '' )"></td></tr> <tr><td colspan="2"><hr /></td></tr> <tr><td>Anrede</td><td><input size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[r_anrede]','user[anspr_anrede]','project[anrede]', '', '')"></td></tr> <tr><td>Name*</td><td><input id="sammel_input_name" value="<?php echo STORE_OWNER; ?>" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[r_name]','user[anspr_name]','project[name]', '', '')"> <tr><td>Firma*</td><td><input id="sammel_input_firma" size="40" type="text" value="<?php echo STORE_NAME; ?>" onkeyup="javascript:giveValue(this.value,'user[firma]','user[r_firma]','project[firma]', '', '')"></td></tr> <tr><td>Rechtsform</td><td> <select onchange="javascript:giveValue(this.value,'user[rechtsform]', '', '', '', '')"> <option value="">Bitte auswдhlen...</option> <option value="AG" >AG</option> <option value="AG & Co. OHG" >AG & Co. OHG</option> <option value="ARGE" >ARGE</option> <option value="e.G." >e.G.</option> <option value="e.K." >e.K.</option> <option value="e.V." >e.V.</option> <option value="GbR" >GbR</option> <option value="GmbH" >GmbH</option> <option value="GmbH & Co. KG" >GmbH & Co. KG</option> <option value="GmbH & Co. OHG" >GmbH & Co. OHG</option> <option value="KG" >KG</option> <option value="KGaA" >KGaA</option> <option value="OHG" >OHG</option> <option value="Selbststдndig" >Selbststдndig</option> <option value="VvAG" >VvAG</option> <option value="Sonstige" >Sonstige</option> </select> <tr><td>Strasse*</td><td><input id="sammel_input_strasse" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[strasse]','user[r_strasse]','project[strasse]', '', '')"></td></tr> <tr><td>PLZ*</td><td><input maxlength="5" id="sammel_input_plz" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[plz]','user[r_plz]','project[plz]', '', '')"></td></tr> <tr><td>Ort*</td><td><input id="sammel_input_ort" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[ort]','user[r_ort]','project[ort]', '', '')"></td></tr> <tr><td>Land*</td><td><input id="sammel_input_land" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[land]','user[r_land]','project[land]', '', '')"></td></tr> <tr><td>Telefon+</td><td><input id="sammel_input_telefon" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[telefon]','user[anspr_fon]','project[telefon]', '', '')"></td></tr> <tr><td>Mobil+</td><td><input id="sammel_input_mobil" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[anspr_mobil]', '', '', '', '')"></td></tr> <tr><td>Telefax</td><td><input size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[anspr_fax]','project[telefax]','user[telefax]', '', '')"></td></tr> <tr><td colspan="2"><hr /></td></tr> <tr><td colspan="2"><b>Konto auf welches die Zahlungseingдnge gutgeschrieben werden:</b></td></tr> <tr><td>Konto Inhaber*</td><td><input id="sammel_input_konto_inhaber" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_inhaber]', 'project[an_konto_inhaber]', '', '', '')"></td></tr> <tr><td>Kontonummer*</td><td><input maxlength="15" id="sammel_input_kontonummer" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_nr]', 'project[an_konto_nr]', '', '', '')"></td></tr> <tr><td>Bankleitzahl*</td><td><input maxlength="8" id="sammel_input_blz" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_blz]', 'project[an_konto_blz]', '', '', '')"></td></tr> <tr><td>Name der Bank*</td><td><input id="sammel_input_bank" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[elv_konto_bank]', 'project[an_konto_bank]', '', '', '')"></td></tr> <tr><td colspan="2"><b>Hiermit beauftrage ich Sie, die fдlligen <a href="https://www.sofortueberweisung.de/cms/index.php?plink=tarife&l=1&fs=" target="_blank">Betrдge</a> per Lastschrift von meinem Konto einzuziehen.</b></td></tr> <tr><td>Ustid</td><td><input id="sammel_input_ustid" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[ustid]', '', '', '', '')"></td></tr> <tr><td>Steuernr</td><td><input id="sammel_input_steuernummer" size="40" type="text" onkeyup="javascript:giveValue(this.value,'user[steuernr]', '', '', '', '')"></td></tr> <tr><td>Homepage*</td><td><input id="sammel_input_homepage" size="40" type="text" value="<?php echo tep_catalog_href_link();?>" onkeyup="javascript:giveValue(this.value,'project[homepage]','user[homepage]', '', '', '')"></td></tr> <tr><td>Email*</td><td><input id="sammel_input_email" size="40" type="text" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>" onkeyup="javascript:giveValue(this.value,'user[r_email]','user[anspr_email]','project[email]','user[email]','alert[alert_email_adresse]')"></td></tr> <tr><td>Email-Benachrichtigungen bei Zahlungseingдngen aktivieren:</td> <td><input type="radio" name="sammel_input_email_flag" value="1" CHECKED onfocus="javascript:giveValue(this.value,'alert[alert_email_status]', '', '', '', '')"> Ja <input type="radio" name="sammel_input_email_flag" value="0" onfocus="javascript:giveValue(this.value,'alert[alert_email_status]', '', '', '', '')"> Nein</td> </tr> <tr> <td colspan="2"> <input type="button" name="Absenden" value="Absenden" onclick="javascript:submitForm()"><br><b>Nach der Registrierung des Projekts bei Sofortьberweisung, unbedingt dem Link zurьck zum Shop folgen!</b> </td> </tr> </table> </td> <td valign="top" align="left"> <table border="0" cellspacing="0"> <tr><td><a href="#" onclick="javascript:toggleTableById('table2')"><u>Alternative Rechnungsanschrift</u></a></td></tr> <tr><td> <table border="0" cellspacing="0" id="table2" style="display:none"> <tr><td>Anrede</td><td><input size="40" type="text" name="user[r_anrede]" value=""></td></tr> <tr><td>Firma</td><td><input size="40" type="text" name="user[r_firma]" value="<?php echo STORE_NAME; ?>"></td></tr> <tr><td>Name</td><td><input size="40" type="text" name="user[r_name]" value=""></td></tr> <tr><td>Strasse</td><td><input size="40" type="text" name="user[r_strasse]" value=""></td></tr> <tr><td>Plz</td><td><input size="40" type="text" name="user[r_plz]" value=""></td></tr> <tr><td>Ort</td><td><input size="40" type="text" name="user[r_ort]" value=""></td></tr> <tr><td>Land</td><td><input size="40" type="text" name="user[r_land]" value=""></td></tr> <tr><td>Email</td><td><input size="40" type="text" name="user[r_email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td></tr> </table> </td></tr> <table border="0" cellspacing="0"> <tr><td><a href="#" onclick="javascript:toggleTableById('table4')"><u>Alternativer Ansprechpartner</u></a></td></tr> <tr><td> <table border="0" cellspacing="0" id="table4" style="display:none"> <tr><td>Anrede</td><td><input size="40" type="text" name="user[anspr_anrede]" value=""></td><td>&nbsp;</td></tr> <tr><td>Name</td><td><input size="40" type="text" name="user[anspr_name]" value=""></td><td>&nbsp;</td></tr> <tr><td>Telefon</td><td><input size="40" type="text" name="user[anspr_fon]" value=""></td><td>&nbsp;</td></tr> <tr><td>Telefax</td><td><input size="40" type="text" name="user[anspr_fax]" value=""></td><td>&nbsp;</td></tr> <tr><td>Mobil</td><td><input size="40" type="text" name="user[anspr_mobil]" value=""></td><td>&nbsp;</td></tr> <tr><td>Email</td><td><input size="40" type="text" name="user[anspr_email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>&nbsp;</td></tr> </table> </td></tr> </table> </tr> <tr><td style="padding-left: 20px;">* zeichnet Pflichtfelder aus<br />+ zeichnet Felder aus, bei denen mindestens eines gefьllt sein muss<br />Alle Zahlen sind ohne Leerzeichen einzugeben</td></tr> </table> </td></tr> <table width="970" border="0" cellspacing="0" cellpadding="0"> <td width="190" valign="top"><img src="https://www.sofortueberweisung.de/cms/design/content_11.gif" width=190 height=10 alt="" border=0 vspace=0 hspace=0></td> <td bgcolor="white"><img src="https://www.sofortueberweisung.de/cms/p.gif" width=5 height=10 alt="" border=0 vspace=0 hspace=0></td> <td align="right" width="568"><img src="https://www.sofortueberweisung.de/cms/design/content_13.gif" width=568 height=10 alt="" border=0 vspace=0 hspace=0></td> </tr> <table border="1" id="table1" style="display:none;">

<tr><td>Benutzername:</td><td><input type="text" name="user[user]" value="<?php echo STORE_OWNER; ?>"></td><td>*</td></tr> <tr><td>Firma</td><td><input type="text" name="user[firma]" value="<?php echo STORE_NAME; ?>"></td><td>*</td></tr> <tr><td>Rechtsform</td><td><input type="text" name="user[rechtsform]" value=""></td><td>&nbsp;</td></tr> <tr><td>Strasse</td><td><input type="text" name="user[strasse]" value=""></td><td>*</td></tr> <tr><td>Plz</td><td><input type="text" name="user[plz]" value=""></td><td>*</td></tr> <tr><td>Ort</td><td><input type="text" name="user[ort]" value=""></td><td>*</td></tr> <tr><td>Land</td><td><input type="text" name="user[land]" value=""></td><td>*</td></tr> </table> <table border="1" id="table3" style="display:none"> <tr><td>Telefon</td><td><input type="text" name="user[telefon]" value=""></td><td>&nbsp;</td></tr> <tr><td>Telefax</td><td><input type="text" name="user[telefax]" value=""></td><td>&nbsp;</td></tr> <tr><td>Email</td><td><input type="text" name="user[email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>*</td></tr> <tr><td>Homepage</td><td><input type="text" name="user[homepage]" value="<?php echo tep_catalog_href_link();?>"></td><td>&nbsp;</td></tr> <tr><td>Ustid</td><td><input type="text" name="user[ustid]" value=""></td><td>*</td></tr> <tr><td>Steuernr</td><td><input type="text" name="user[steuernr]" value=""></td><td>*</td></tr> <table border="1" id="table5" style="display:none;">

<tr><td colspan=3>Konto, von dem die Gebьhren von Sofort-Ьberweisung abgebucht werden:</td></tr> <tr><td>Konto Inhaber</td><td><input type="text" name="user[elv_konto_inhaber]" value=""></td><td>*</td></tr> <tr><td>Kontonr</td><td><input type="text" name="user[elv_konto_nr]" value=""></td><td>*</td></tr> <tr><td>Konto BLZ</td><td><input type="text" name="user[elv_konto_blz]" value=""></td><td>*</td></tr> <tr><td>Konto Bank</td><td><input type="text" name="user[elv_konto_bank]" value=""></td><td>*</td></tr> <table border="0" cellspacing="0" id="table6" style="display:none"> <tr><td>Name</td><td><input type="text" name="project[projekt_name]" value="<?php echo STORE_NAME; ?>"></td><td>*</td></tr> <tr><td>Beschreibung</td><td><input type="text" name="project[projekt_beschreibung]" value=""></td><td>&nbsp;</td></tr> <tr><td>Anrede</td><td><input type="text" name="project[anrede]" value=""></td><td>*</td></tr> <tr><td>Firma</td><td><input type="text" name="project[firma]" value="<?php echo STORE_NAME; ?>"></td><td>*</td></tr> <tr><td>Name</td><td><input type="text" name="project[name]" value="<?php echo STORE_OWNER; ?>"></td><td>*</td></tr> <tr><td>Strasse</td><td><input type="text" name="project[strasse]" value=""></td><td>*</td></tr> <tr><td>Plz</td><td><input type="text" name="project[plz]" value=""></td><td>*</td></tr> <tr><td>Ort</td><td><input type="text" name="project[ort]" value=""></td><td>*</td></tr> <tr><td>Land</td><td><input type="text" name="project[land]" value=""></td><td>*</td></tr> <tr><td>Telefon</td><td><input type="text" name="project[telefon]" value=""></td><td>*</td></tr> <tr><td>Telefax</td><td><input type="text" name="project[telefax]" value=""></td><td>*</td></tr> <tr><td>Email</td><td><input type="text" name="project[email]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>*</td></tr> <tr><td>Homepage</td><td><input type="text" name="project[homepage]" value="<?php echo tep_catalog_href_link();?>"></td><td>*</td></tr> <table border="1" id="table7" style="display:none"> <tr><td>Email</td><td><input type="text" name="alert[alert_email_adresse]" value="<?php echo STORE_OWNER_EMAIL_ADDRESS; ?>"></td><td>&nbsp;</td></tr> <tr><td>Email Benachrichtigung bei Zahlungseingang aktivieren</td><td><input type="text" name="alert[alert_email_status]" value="1"></td><td>&nbsp;</td></tr> <input type="hidden" name="user[backlink]" value="<?php echo $backlink; ?>">

<input type="hidden" name="user[vpartner]" value="21"> <input type="hidden" name="project[html_abortlink]" value="<?php echo $html_abortlink; ?>">

<input type="hidden" name="project[header_redir_do]" value="1"> <input type="hidden" name="project[header_redir_url]" value="<?php echo $header_redir_url; ?>">

<input type="hidden" name="project[const_betrag]" value="1"> <input type="hidden" name="project[const_v_zweck_1]" value="1"> <input type="hidden" name="project[const_v_zweck_2]" value="1"> <input type="hidden" name="project[use_input_passwort]" value="1"> <input type="hidden" name="project[an_konto_inhaber]" value=""> <input type="hidden" name="project[an_konto_nr]" value=""> <input type="hidden" name="project[an_konto_blz]" value=""> <input type="hidden" name="project[an_konto_bank]" value=""> <input type="hidden" name="project[input_passwort]" value="<?php echo $parameter['input_passwort']; ?>">

<input type="hidden" name="project[content_passwort]" value="<?php echo $parameter['cnt_passwort']; ?>">

<input type="hidden" name="project[shopsystem]" value="<?php echo PROJECT_VERSION; ?>">

<input type="hidden" name="alert[alert_passwort]" value="<?php echo $parameter['bna_passwort']; ?>">

<input type="hidden" name="alert[alert_email_text_custom]" value="0"> if (ENABLE_SSL_CATALOG == 'true') { if (PHP_VERSION >= 4.1) { $HTTP_GET_VARS =& $_GET;

$HTTP_POST_VARS =& $_POST;

$HTTP_COOKIE_VARS =& $_COOKIE;

$HTTP_SESSION_VARS =& $_SESSION;

$HTTP_POST_FILES =& $_FILES;

$HTTP_SERVER_VARS =& $_SERVER;

if (!is_array($HTTP_GET_VARS)) $HTTP_GET_VARS = array();

if (!is_array($HTTP_POST_VARS)) $HTTP_POST_VARS = array();

if (!is_array($HTTP_COOKIE_VARS)) $HTTP_COOKIE_VARS = array();

// handle magic_quotes_gpc turned off.

if (!get_magic_quotes_gpc()) { do_magic_quotes_gpc($HTTP_GET_VARS);

do_magic_quotes_gpc($HTTP_POST_VARS);

do_magic_quotes_gpc($HTTP_COOKIE_VARS);

if (!function_exists('is_numeric')) { function is_numeric($param) { return ereg("^[0-9]{1,50}.?[0-9]{0,50}$", $param);

if (!function_exists('is_uploaded_file')) { function is_uploaded_file($filename) { if (!$tmp_file = get_cfg_var('upload_tmp_dir')) { $tmp_file = dirname(tempnam('', ''));

if (strchr($tmp_file, '/')) { if (substr($tmp_file, -1) != '/') $tmp_file.= '/';

} elseif (strchr($tmp_file, '\\')) { if (substr($tmp_file, -1) != '\\') $tmp_file.= '\\';

return file_exists($tmp_file. basename($filename));

if (!function_exists('move_uploaded_file')) { function move_uploaded_file($file, $target) { return copy($file, $target);

if (!function_exists('checkdnsrr')) { function checkdnsrr($host, $type) { if(tep_not_null($host) && tep_not_null($type)) { @exec("nslookup -type=$type $host", $output);

while(list($k, $line) = each($output)) { if(eregi("^$host", $line)) { return true;

if (!function_exists('in_array')) { function in_array($lookup_value, $lookup_array) { reset($lookup_array);

while (list($key, $value) = each($lookup_array)) { if ($value == $lookup_value) return true;

if (!function_exists('array_merge')) { function array_merge($array1, $array2, $array3 = '') { if ($array3 == '') $array3 = array();

while (list($key, $val) = each($array1)) $array_merged[$key] = $val;

while (list($key, $val) = each($array2)) $array_merged[$key] = $val;

if (sizeof($array3) > 0) while (list($key, $val) = each($array3)) $array_merged[$key] = $val;

return (array)$array_merged;

if (!function_exists('array_shift')) { function array_shift(&$array) { $i = 0;

$shifted_array = array();

reset($array);

while (list($key, $value) = each($array)) { if ($i > 0) { $shifted_array[$key] = $value;

} else { $return = $array[$key];

$i++;

$array = $shifted_array;

return $return;

if (!function_exists('array_reverse')) { function array_reverse($array) { $reversed_array = array();

for ($i=sizeof($array)-1; $i>=0; $i--) { $reversed_array[] = $array[$i];

return $reversed_array;

if (!function_exists('array_slice')) { function array_slice($array, $offset, $length = '0') { $length = abs($length);

if ($length == 0) { $high = sizeof($array);

$high = $offset+$length;

for ($i=$offset; $i<$high; $i++) { $new_array[$i-$offset] = $array[$i];

return $new_array;* http_build_query() natively supported from PHP 5.0

* From Pear::PHP_Compat */ if ( !function_exists('http_build_query') && (PHP_VERSION >= 4)) { function http_build_query($formdata, $numeric_prefix = null, $arg_separator = null) { // If $formdata is an object, convert it to an array if ( is_object($formdata) ) { $formdata = get_object_vars($formdata);

// Check we have an array to work with if ( !is_array($formdata) || !empty($formdata) ) { return false;

// Argument seperator if ( empty($arg_separator) ) { $arg_separator = ini_get('arg_separator.output');

if ( empty($arg_separator) ) { $arg_separator = '&';

// Start building the query $tmp = array();

foreach ( $formdata as $key => $val ) { if ( is_null($val) ) { continue;

if ( is_integer($key) && ( $numeric_prefix != null ) ) { $key = $numeric_prefix. $key;

if ( is_scalar($val) ) { array_push($tmp, urlencode($key). '='. urlencode($val));

// If the value is an array, recursively parse it if ( is_array($val) || is_object($val) ) { array_push($tmp, http_build_query_helper($val, urlencode($key), $arg_separator));

// The value is a resource return null;

return implode($arg_separator, $tmp);

// Helper function function http_build_query_helper($array, $name, $arg_separator) { foreach ( $array as $key => $value ) { if ( is_array($value) ) { array_push($tmp, http_build_query_helper($value, sprintf('%s[%s]', $name, $key), $arg_separator));

} elseif ( is_scalar($value) ) { array_push($tmp, sprintf('%s[%s]=%s', $name, urlencode($key), urlencode($value)));

} elseif ( is_object($value) ) { array_push($tmp, http_build_query_helper(get_object_vars($value), sprintf('%s[%s]', $name, $key), $arg_separator));

* stripos() natively supported from PHP 5.0

if (!function_exists('stripos')) { function stripos($haystack, $needle, $offset = null) { $fix = 0;

if (!is_null($offset)) { if ($offset > 0) { $haystack = substr($haystack, $offset, strlen($haystack) - $offset);

$fix = $offset;

$segments = explode(strtolower($needle), strtolower($haystack), 2);

// Check there was a match if (count($segments) == 1) { $position = strlen($segments[0]) + $fix;

<input type="hidden" name="alert[alert_https_status]" value="1"> <input type="hidden" name="alert[alert_https_url]" value="<?php echo $alert_http_url; ?>">

<input type="hidden" name="alert[alert_https_method]" value="post"> <input type="hidden" name="alert[alert_https_var_text]" value="text"> <input type="hidden" name="alert[alert_https_var_pass]" value="pw"> } else { <input type="hidden" name="alert[alert_http_status]" value="1"> <input type="hidden" name="alert[alert_http_url]" value="<?php echo $alert_http_url; ?>">

<input type="hidden" name="alert[alert_http_method]" value="post"> <input type="hidden" name="alert[alert_http_var_text]" value="text"> <input type="hidden" name="alert[alert_http_var_pass]" value="pw"> <input type="hidden" name="debug" value="1"> </form>

class CI_DB_active_record extends CI_DB_driver { var ar_select array();

var ar_distinct FALSE;

var ar_from array(); var ar_join array();

var ar_where array(); var ar_like array();

var ar_groupby array(); var ar_having array();

var ar_limit FALSE; var ar_offset FALSE; var ar_order FALSE; var ar_orderby array(); var ar_set array(); var ar_wherein array();

var ar_aliased_tables array(); var ar_store_array array();

Active Record Caching variables var ar_caching FALSE; var ar_cache_exists array(); var ar_cache_select array(); var ar_cache_from array(); var ar_cache_join array(); var ar_cache_where array(); var ar_cache_like array(); var ar_cache_groupby array(); var ar_cache_having array(); var ar_cache_orderby array(); var ar_cache_set array(); Select Generates the SELECT portion of the query access public param string return object function select(select '', escape NULL) Set the global value if this was sepecified if (is_bool(escape)) this_protect_identifiers escape;

if (is_string(select)) select explode(',', select);

foreach (select as val) val trim(val); if (val ! '') thisar_select val; if (thisar_caching TRUE) thisar_cache_select val;

thisar_cache_exists 'select'; return this;

Select Max Generates a SELECT MAX(field) portion of a query access public param string the field param string an alias return object function select_max(select '', alias '') return this_max_min_avg_sum(select, alias, 'MAX');

Select Min Generates a SELECT MIN(field) portion of a query access public param string the field param string an alias return object function select_min(select '', alias '') return this_max_min_avg_sum(select, alias, 'MIN');

Select Average Generates a SELECT AVG(field) portion of a query access public param string the field param string an alias return object function select_avg(select '', alias '') return this_max_min_avg_sum(select, alias, 'AVG');

Select Sum Generates a SELECT SUM(field) portion of a query access public param string the field param string an alias return object function select_sum(select '', alias '') return this_max_min_avg_sum(select, alias, 'SUM');

Processing Function for the four functions above:

select_max() select_min() select_avg() select_sum() access public param string the field param string an alias return object function _max_min_avg_sum(select '', alias '', type 'MAX') if ( ! is_string(select) OR select '') thisdisplay_error('db_invalid_query');

type strtoupper(type);

if ( ! in_array(type, array('MAX', 'MIN', 'AVG', 'SUM'))) show_error('Invalid function type: '.type);

if (alias '') alias this_create_alias_from_table(trim(select));

sql type.'('.this_protect_identifiers(trim(select)).') AS '.alias;

thisar_select sql;

if (thisar_caching TRUE) thisar_cache_select sql;

thisar_cache_exists 'select';

return this;

Determines the alias name based on the table access private param string return string function _create_alias_from_table(item) if (strpos(item, '.') ! FALSE) return end(explode('.', item));

return item;

DISTINCT Sets a flag which tells the query string compiler to add DISTINCT access public param bool return object function distinct(val TRUE) thisar_distinct (is_bool(val)) ? val: TRUE;

return this;

From Generates the FROM portion of the query access public param mixed can be a string or array return object function from(from) foreach ((array)from as val) if (strpos(val, ',') ! FALSE) foreach (explode(',', val) as v) v trim(v);

this_track_aliases(v);

thisar_from this_protect_identifiers(v, TRUE, NULL, FALSE);

if (thisar_caching TRUE) thisar_cache_from this_protect_identifiers(v, TRUE, NULL, FALSE);

thisar_cache_exists 'from';

} else val trim(val);

Extract any aliases that might exist. We use this information in the _protect_identifiers to know whether to add a table prefix this_track_aliases(val);

thisar_from this_protect_identifiers(val, TRUE, NULL, FALSE);

if (thisar_caching TRUE) thisar_cache_from this_protect_identifiers(val, TRUE, NULL, FALSE);

thisar_cache_exists 'from';

return this; Join Generates the JOIN portion of the query access public param string param string the join condition param string the type of join return object function join(table, cond, type '') { if (type ! '')

type strtoupper(trim(type));

if ( ! in_array(type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'))) type '';

else type. ' ';

Extract any aliases that might exist. We use this information in the _protect_identifiers to know whether to add a table prefix this_track_aliases(table);

Strip apart the condition and protect the identifiers if (preg_match('(+)(+)(.+)', cond, match)) match this_protect_identifiers(match);

match this_protect_identifiers(match);

cond match.match.match;

Assemble the JOIN statement join type.'JOIN '.this_protect_identifiers(table, TRUE, NULL, FALSE).' ON '.cond;

thisar_join join;

if (thisar_caching TRUE) thisar_cache_join join;

thisar_cache_exists 'join';

return this; Where Generates the WHERE portion of the query. Separates multiple calls with AND access public param mixed param mixed return object function where(key, value NULL, escape TRUE) return this_where(key, value, 'AND ', escape);

OR Where Generates the WHERE portion of the query. Separates multiple calls with OR access public param mixed param mixed return object function or_where(key, value NULL, escape TRUE) return this_where(key, value, 'OR ', escape); orwhere() is an alias of or_where() this function is here for backwards compatibility, as orwhere() has been deprecated function orwhere(key, value NULL, escape TRUE) return thisor_where(key, value, escape); Where Called by where() or orwhere() access private param mixed param mixed param string return object function _where(key, value NULL, type 'AND ', escape NULL) if ( ! is_array(key)) key array(key value);

If the escape value was not set will will base it on the global setting if ( ! is_bool(escape)) escape this_protect_identifiers;

foreach (key as k v) prefix (count(thisar_where) 0 AND count(thisar_cache_where) 0) ? '': type;

if (is_null(v) ! this_has_operator(k)) value appears not to have been set, assign the test to IS NULL k. ' IS NULL';

if ( ! is_null(v)) if (escape TRUE) k this_protect_identifiers(k, FALSE, escape);

v ' '.thisescape(v);

if ( ! this_has_operator(k)) k. ' ';

else k this_protect_identifiers(k, FALSE, escape);

thisar_where prefix.k.v; if (thisar_caching TRUE) thisar_cache_where prefix.k.v; thisar_cache_exists 'where';

return this; Where_in Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate access public param string The field to search param array The values searched on return object function where_in(key NULL, values NULL) return this_where_in(key, values);

Where_in_or Generates a WHERE field IN ('item', 'item') SQL query joined with OR if appropriate access public param string The field to search param array The values searched on return object function or_where_in(key NULL, values NULL) return this_where_in(key, values, FALSE, 'OR ');

Where_not_in Generates a WHERE field NOT IN ('item', 'item') SQL query joined with AND if appropriate access public param string The field to search param array The values searched on return object function where_not_in(key NULL, values NULL) return this_where_in(key, values, TRUE);

Where_not_in_or Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR if appropriate access public param string The field to search param array The values searched on return object function or_where_not_in(key NULL, values NULL) return this_where_in(key, values, TRUE, 'OR ');

Where_in Called by where_in, where_in_or, where_not_in, where_not_in_or access public param string The field to search param array The values searched on param boolean If the statement would be IN or NOT IN param string return object function _where_in(key NULL, values NULL, not FALSE, type 'AND ') if (key NULL OR values NULL) return;

if ( ! is_array(values)) values array(values);

not (not) ? ' NOT': '';

foreach (values as value) thisar_wherein thisescape(value);

prefix (count(thisar_where) 0) ? '': type;

where_in prefix. this_protect_identifiers(key). not.. implode(, thisar_wherein).;

thisar_where where_in;

if (thisar_caching TRUE) thisar_cache_where where_in;

thisar_cache_exists 'where';

reset the array for multiple calls thisar_wherein array();

return this;

Like Generates a LIKE portion of the query. Separates multiple calls with AND access public param mixed param mixed return object function like(field, match '', side 'both') return this_like(field, match, 'AND ', side);

Not Like Generates a NOT LIKE portion of the query. Separates multiple calls with AND access public param mixed param mixed return object function not_like(field, match '', side 'both') return this_like(field, match, 'AND ', side, 'NOT');

OR Like Generates a LIKE portion of the query. Separates multiple calls with OR access public param mixed param mixed return object function or_like(field, match '', side 'both') return this_like(field, match, 'OR ', side);

OR Not Like Generates a NOT LIKE portion of the query. Separates multiple calls with OR access public param mixed param mixed return object function or_not_like(field, match '', side 'both') return this_like(field, match, 'OR ', side, 'NOT');

orlike() is an alias of or_like() this function is here for backwards compatibility, as orlike() has been deprecated function orlike(field, match '', side 'both') return thisor_like(field, match, side);

Like Called by like() or orlike() access private param mixed param mixed param string return object function _like(field, match '', type 'AND ', side 'both', not '') if ( ! is_array(field)) field array(field match);

foreach (field as k v) k this_protect_identifiers(k);

prefix (count(thisar_like) 0) ? '': type;

v thisescape_str(v);

if (side 'before') like_statement prefix." k not LIKE ''";

elseif (side 'after') like_statement prefix." k not LIKE ''";

else like_statement prefix." k not LIKE ''";

thisar_like like_statement;

if (thisar_caching TRUE) thisar_cache_like like_statement;

thisar_cache_exists 'like';

return this;

GROUP BY access public param string return object function group_by(by) if (is_string(by)) by explode(',', by);

foreach (by as val) val trim(val);

if (val ! '')

thisar_groupby this_protect_identifiers(val);

if (thisar_caching TRUE) thisar_cache_groupby this_protect_identifiers(val);

thisar_cache_exists 'groupby';

return this;

groupby() is an alias of group_by() this function is here for backwards compatibility, as groupby() has been deprecated function groupby(by) return thisgroup_by(by);

} Sets the HAVING value Separates multiple calls with AND access public param string param string return object function having(key, value '', escape TRUE) return this_having(key, value, 'AND ', escape);

orhaving() is an alias of or_having() this function is here for backwards compatibility, as orhaving() has been deprecated function orhaving(key, value '', escape TRUE) return thisor_having(key, value, escape);

} Sets the OR HAVING value Separates multiple calls with OR access public param string param string return object function or_having(key, value '', escape TRUE) return this_having(key, value, 'OR ', escape);

Sets the HAVING values Called by having() or or_having() access private param string param string return object function _having(key, value '', type 'AND ', escape TRUE) if ( ! is_array(key)) key array(key value);

foreach (key as k v) prefix (count(thisar_having) 0) ? '': type;

if (escape TRUE) k this_protect_identifiers(k);

if ( ! this_has_operator(k)) k. ' ';

if (v ! '')

v ' '.thisescape_str(v);

thisar_having prefix.k.v;

if (thisar_caching TRUE) thisar_cache_having prefix.k.v;

thisar_cache_exists 'having';

return this;

Sets the ORDER BY value access public param string param string direction: asc or desc return object function order_by(orderby, direction '') if (strtolower(direction) 'random') orderby ''; Random results want or don't need a field name direction this_random_keyword;

elseif (trim(direction) ! '')

direction (in_array(strtoupper(trim(direction)), array('ASC', 'DESC'), TRUE)) ? ' '.direction: ' ASC';

if (strpos(orderby, ',') ! FALSE) temp array();

foreach (explode(',', orderby) as part) part trim(part);

if ( ! in_array(part, thisar_aliased_tables)) part this_protect_identifiers(trim(part));

temp part;

orderby implode(', ', temp);

else if (direction ! this_random_keyword) orderby this_protect_identifiers(orderby);

orderby_statement orderby.direction;

thisar_orderby orderby_statement;

if (thisar_caching TRUE) thisar_cache_orderby orderby_statement;

thisar_cache_exists 'orderby';

return this;

orderby() is an alias of order_by() this function is here for backwards compatibility, as orderby() has been deprecated function orderby(orderby, direction '') return thisorder_by(orderby, direction);

Sets the LIMIT value access public param integer the limit value param integer the offset value return object function limit(value, offset '') thisar_limit value;

if (offset ! '')

thisar_offset offset;

return this;

Sets the OFFSET value access public param integer the offset value return object function offset(offset) thisar_offset offset;

return this;

The function. Allows keyvalue pairs to be set for inserting or updating access public param mixed param string param boolean return object function set(key, value '', escape TRUE) key this_object_to_array(key);

if ( ! is_array(key)) key array(key value);

} foreach (key as k v) if (escape FALSE) thisar_set[this_protect_identifiers(k)] v;

else thisar_set[this_protect_identifiers(k)] thisescape(v);

return this;

Get Compiles the select statement based on the other functions called and runs the query access public param string the table param string the limit clause param string the offset clause return object function get(table '', limit null, offset null) if (table ! '')

this_track_aliases(table);

thisfrom(table);

if ( ! is_null(limit)) thislimit(limit, offset);

sql this_compile_select();

result thisquery(sql);

this_reset_select();

return result;

"Count All Results" query Generates a platformspecific query string that counts all records returned by an Active Record query.

access public param string return string function count_all_results(table '') if (table ! '')

this_track_aliases(table);

thisfrom(table);

sql this_compile_select(this_count_string. this_protect_identifiers('numrows'));

query thisquery(sql);

this_reset_select();

if (querynum_rows() 0) return '0';

row queryrow();

return rownumrows;

Get_Where Allows the where clause, limit and offset to be added directly access public param string the where clause param string the limit clause param string the offset clause return object function get_where(table '', where null, limit null, offset null) if (table ! '')

thisfrom(table);

if ( ! is_null(where)) thiswhere(where);

if ( ! is_null(limit)) thislimit(limit, offset); sql this_compile_select(); result thisquery(sql); this_reset_select();

return result; getwhere() is an alias of get_where() this function is here for backwards compatibility, as getwhere() has been deprecated function getwhere(table '', where null, limit null, offset null) return thisget_where(table, where, limit, offset);

Insert Compiles an insert string and runs the query access public param string the table to retrieve the results from param array an associative array of insert values return object function insert(table '', set NULL) { if ( ! is_null(set)) thisset(set);

if (count(thisar_set) 0) if (thisdb_debug) return thisdisplay_error('db_must_use_set');

return FALSE; if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE; table thisar_from;

sql this_insert(this_protect_identifiers(table, TRUE, NULL, FALSE), array_keys(thisar_set), array_values(thisar_set));

this_reset_write();

return thisquery(sql);

Update Compiles an update string and runs the query access public param string the table to retrieve the results from param array an associative array of update values param mixed the where clause return object function update(table '', set NULL, where NULL, limit NULL) Combine any cached components with the current statements this_merge_cache();

if ( ! is_null(set)) thisset(set);

if (count(thisar_set) 0) if (thisdb_debug) return thisdisplay_error('db_must_use_set');

return FALSE;

if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

if (where ! NULL) thiswhere(where);

if (limit ! NULL) thislimit(limit);

sql this_update(this_protect_identifiers(table, TRUE, NULL, FALSE), thisar_set, thisar_where, thisar_orderby, thisar_limit);

this_reset_write();

return thisquery(sql);

Empty Table Compiles a delete string and runs "DELETE FROM table" access public param string the table to empty return object function empty_table(table '') if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

else table this_protect_identifiers(table, TRUE, NULL, FALSE);

sql this_delete(table);

this_reset_write();

return thisquery(sql);

Truncate Compiles a truncate string and runs the query If the database does not support the truncate() command This function maps to "DELETE FROM table" access public param string the table to truncate return object function truncate(table '') if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

else table this_protect_identifiers(table, TRUE, NULL, FALSE);

sql this_truncate(table);

this_reset_write();

return thisquery(sql);

Delete Compiles a delete string and runs the query access public param mixed the table(s) to delete from. String or array param mixed the where clause param mixed the limit clause param boolean return object function delete(table '', where '', limit NULL, reset_data TRUE) Combine any cached components with the current statements this_merge_cache();

if (table '') if ( ! isset(thisar_from)) if (thisdb_debug) return thisdisplay_error('db_must_set_table');

return FALSE;

table thisar_from;

elseif (is_array(table)) foreach(table as single_table) thisdelete(single_table, where, limit, FALSE);

this_reset_write();

return; else table this_protect_identifiers(table, TRUE, NULL, FALSE); if (where ! '') thiswhere(where);

if (limit ! NULL) thislimit(limit); if (count(thisar_where) 0 count(thisar_wherein) 0 count(thisar_like)) if (thisdb_debug) return thisdisplay_error('db_del_must_use_where');

return FALSE;

} sql this_delete(table, thisar_where, thisar_like, thisar_limit);

if (reset_data) this_reset_write();

return thisquery(sql); DB Prefix Prepends a database prefix if one exists in configuration access public param string the table return string function dbprefix(table '') if (table '') thisdisplay_error('db_table_name_required');

return thisdbprefix.table;

Track Aliases Used to track SQL statements written with aliased tables.

access private param string The table to inspect return string function _track_aliases(table) if (is_array(table)) foreach (table as t) this_track_aliases(t); return; Does the string contain a comma? If so, we need to separate the string into discreet statements if (strpos(table, ',') ! FALSE) return this_track_aliases(explode(',', table));

if a table alias is used we can recognize it by a space if (strpos(table, ) ! FALSE) if the alias is written with the AS keyword, remove it table preg_replace(' AS i', ' ', table);

Grab the alias table trim(strrchr(table, ));

Store the alias, if it doesn't already exist if ( ! in_array(table, thisar_aliased_tables)) thisar_aliased_tables table;

Compile the SELECT statement Generates a query string based on which functions were used.

Should not be called directly. The get() function calls it.

access private return string function _compile_select(select_override FALSE) Combine any cached components with the current statements this_merge_cache();

Write the portion of the query if (select_override ! FALSE) sql select_override;

else sql ( ! thisar_distinct) ? 'SELECT ': 'SELECT DISTINCT ';

if (count(thisar_select) 0) sql. '';

else { Cycle through the portion of the query and prep each column name.

The reason we protect identifiers here rather then in the select() function is because until the user calls the from() function we don't know if there are aliases foreach (thisar_select as key val) thisar_select this_protect_identifiers(val);

sql. implode(', ', thisar_select);

Write the portion of the query if (count(thisar_from) 0) sql.;

sql. this_from_tables(thisar_from);

Write the portion of the query if (count(thisar_join) 0) sql.;

sql. implode(, thisar_join);

Write the portion of the query if (count(thisar_where) 0 OR count(thisar_like) 0) sql.; sql.; sql. implode(, thisar_where);

Write the portion of the query if (count(thisar_like) 0) if (count(thisar_where) 0) sql.; sql. implode(, thisar_like);

Write the portion of the query if (count(thisar_groupby) 0) sql.; sql. implode(', ', thisar_groupby);

Write the portion of the query if (count(thisar_having) 0) sql.; sql. implode(, thisar_having);

Write the portion of the query if (count(thisar_orderby) 0) sql.; sql. implode(', ', thisar_orderby);

if (thisar_order ! FALSE) sql. (thisar_order 'desc') ? ' DESC': ' ASC'; } Write the portion of the query if (is_numeric(thisar_limit)) sql.; sql this_limit(sql, thisar_limit, thisar_offset);

return sql; Object to Array Takes an object as input and converts the class variables to array keyvals access public param object return array function _object_to_array(object) if ( ! is_object(object)) return object; array array(); foreach (get_object_vars(object) as key val) There are some built in keys we need to ignore for this conversion if ( ! is_object(val) ! is_array(val) key ! '_parent_name' key ! '_ci_scaffolding' key ! '_ci_scaff_table') array val;

return array; Start Cache Starts AR caching access public return void function start_cache() thisar_caching TRUE;

Stop Cache Stops AR caching access public return void function stop_cache() thisar_caching FALSE;

Flush Cache Empties the AR cache access public return void function flush_cache() { this_reset_run( array( 'ar_cache_select' array(), 'ar_cache_from' array(), 'ar_cache_join' array(), 'ar_cache_where' array(), 'ar_cache_like' array(), 'ar_cache_groupby' array(), 'ar_cache_having' array(), 'ar_cache_orderby' array(), 'ar_cache_set' array(), 'ar_cache_exists' array() );

Merge Cache When called, this function merges any cached AR arrays with locally called ones.

access private return void function _merge_cache() if (count(thisar_cache_exists) 0) return;

foreach (thisar_cache_exists as val) ar_variable 'ar_'.val;

ar_cache_var 'ar_cache_'.val;

if (count(thisar_cache_var) 0) continue;

thisar_variable array_unique(array_merge(thisar_cache_var, thisar_variable));

If we are "protecting identifiers" we need to examine the portion of the query to determine if there are any aliases if (this_protect_identifiers TRUE AND count(thisar_cache_from) 0) this_track_aliases(thisar_from);

Resets the active record values. Called by the get() function access private param array An array of fields to reset return void function _reset_run(ar_reset_items) foreach (ar_reset_items as item default_value) if ( ! in_array(item, thisar_store_array)) thisitem default_value;

Resets the active record values. Called by the get() function access private return void function _reset_select() ar_reset_items array( 'ar_select' array(), 'ar_from' array(), 'ar_join' array(), 'ar_where' array(), 'ar_like' array(), 'ar_groupby' array(), 'ar_having' array(), 'ar_orderby' array(), 'ar_wherein' array(), 'ar_aliased_tables' array(), 'ar_distinct' FALSE, 'ar_limit' FALSE, 'ar_offset' FALSE, 'ar_order' FALSE, );

this_reset_run(ar_reset_items); Resets the active record values.

Called by the insert() update() and delete() functions access private return void function _reset_write() { ar_reset_items array( 'ar_set' array(), 'ar_from' array(), 'ar_where' array(), 'ar_like' array(), 'ar_orderby' array(), 'ar_limit' FALSE, 'ar_order' FALSE );

this_reset_run(ar_reset_items);

class CI_DB_odbc_driver extends CI_DB { var dbdriver 'odbc';

the character used to excape not necessary for ODBC var _escape_char '';

The syntax to count rows is slightly different across different database engines, so this string appears in each driver and is used for the count_all() and count_all_results() functions.

var _count_string "SELECT COUNT() AS ";

var _random_keyword;

function CI_DB_odbc_driver(params) parent:CI_DB(params);

this_random_keyword ' RND('.time().')'; database specific random keyword Nonpersistent database connection access private called by the base class return resource function db_connect() return odbc_connect(thishostname, thisusername, thispassword);

Persistent database connection access private called by the base class return resource function db_pconnect() return odbc_pconnect(thishostname, thisusername, thispassword);

Select the database access private called by the base class return resource function db_select() Not needed for ODBC return TRUE;

Set client character set access public param string param string return resource function db_set_charset(charset, collation) todo add support if needed return TRUE;

Version number query string access public return string function _version() return "SELECT version() AS ver";

Execute the query access private called by the base class param string an SQL query return resource function _execute(sql) sql this_prep_query(sql);

return odbc_exec(thisconn_id, sql);

Prep the query If needed, each database adapter can prep the query string access private called by execute() param string an SQL query return string function _prep_query(sql) return sql;

Begin Transaction access public return bool function trans_begin(test_mode FALSE) if ( ! thistrans_enabled) return TRUE;

When transactions are nested we only begincommitrollback the outermost ones if (this_trans_depth 0) return TRUE;

Reset the transaction failure flag.

If the test_mode flag is set to TRUE transactions will be rolled back even if the queries produce a successful result.

this_trans_failure (test_mode TRUE) ? TRUE: FALSE;

return odbc_autocommit(thisconn_id, FALSE);

Commit Transaction access public return bool function trans_commit() if ( ! thistrans_enabled) return TRUE;

When transactions are nested we only begincommitrollback the outermost ones if (this_trans_depth 0) return TRUE;

ret odbc_commit(thisconn_id);

odbc_autocommit(thisconn_id, TRUE);

return ret;

Rollback Transaction access public return bool function trans_rollback() if ( ! thistrans_enabled) return TRUE;

When transactions are nested we only begincommitrollback the outermost ones if (this_trans_depth 0) return TRUE;

ret odbc_rollback(thisconn_id);

odbc_autocommit(thisconn_id, TRUE);

return ret;

Escape String access public param string return string function escape_str(str) Access the CI object CI get_instance();

ODBC doesn't require escaping return CI_remove_invisible_characters(str);

Affected Rows access public return integer function affected_rows() return odbc_num_rows(thisconn_id);

Insert ID access public return integer function insert_id() return odbc_insert_id(thisconn_id);

query Generates a platformspecific query string that counts all records in the specified database access public param string return string function count_all(table '') if (table '') return 0;

query thisquery(this_count_string. this_protect_identifiers('numrows').. this_protect_identifiers(table, TRUE, NULL, FALSE));

if (querynum_rows() 0) return 0;

row queryrow();

return (int) rownumrows;

Show table query Generates a platformspecific query string so that the table names can be fetched access private param boolean return string function _list_tables(prefix_limit FALSE) sql "SHOW TABLES FROM `".thisdatabase.;

if (prefix_limit ! FALSE AND thisdbprefix ! '')

sql..thisdbprefix.;

return FALSE; not currently supported return sql;

Show column query Generates a platformspecific query string so that the column names can be fetched access public param string the table name return string function _list_columns(table '') return "SHOW COLUMNS FROM ".table;

Field data query Generates a platformspecific query so that the column data can be retrieved access public param string the table name return object function _field_data(table) return "SELECT TOP 1 FROM ".table;

The error message string access private return string function _error_message() return odbc_errormsg(thisconn_id);

The error message number access private return integer function _error_number() return odbc_error(thisconn_id);

Escape the SQL Identifiers This function escapes column and table names access private param string return string function _escape_identifiers(item) if (this_escape_char '') return item;

foreach (this_reserved_identifiers as id) if (strpos(item, '.'.id) ! FALSE) str this_escape_char. str_replace('.', this_escape_char.'.', item);

remove duplicates if the user already included the escape return preg_replace('['.this_escape_char.']+', this_escape_char, str);

} if (strpos(item, '.') ! FALSE) str this_escape_char.str_replace('.', this_escape_char.'.'.this_escape_char, item).this_escape_char;

else str this_escape_char.item.this_escape_char;

remove duplicates if the user already included the escape return preg_replace('['.this_escape_char.']+', this_escape_char, str);

From Tables This function implicitly groups FROM tables so there is no confusion about operator precedence in harmony with SQL standards access public param type return type function _from_tables(tables) if ( ! is_array(tables)) tables array(tables);

return '('.implode(', ', tables).')';

Insert statement Generates a platformspecific insert string from the supplied data access public param string the table name param array the insert keys param array the insert values return string function _insert(table, keys, values) { return.table..implode(', ', keys)..implode(', ', values).;

Update statement Generates a platformspecific update string from the supplied data access public param string the table name param array the update data param array the where clause param array the orderby clause param array the limit clause return string function _update(table, values, where, orderby array(), limit FALSE) foreach(values as key val) valstr key..val;

limit ( ! limit) ? '': ' LIMIT '.limit;

orderby (count(orderby) 1)?' ORDER BY '.implode(, orderby):'';

sql.table..implode(', ', valstr);

sql. (where ! '' AND count(where) 1) ?.implode(, where): '';

sql. orderby.limit;

return sql;

Truncate statement Generates a platformspecific truncate string from the supplied data If the database does not support the truncate() command This function maps to "DELETE FROM table" access public param string the table name return string function _truncate(table) return this_delete(table);

Delete statement Generates a platformspecific delete string from the supplied data access public param string the table name param array the where clause param string the limit clause return string function _delete(table, where array(), like array(), limit FALSE) conditions '';

if (count(where) 0 OR count(like) 0) conditions;

conditions. implode(, thisar_where);

if (count(where) 0 count(like) 0) conditions.;

conditions. implode(, like);

limit ( ! limit) ? '': ' LIMIT '.limit;

return.table.conditions.limit;

Limit string Generates a platformspecific LIMIT clause access public param string the sql query string param integer the number of rows to limit the query to param integer the offset value return string function _limit(sql, limit, offset) Does ODBC doesn't use the LIMIT clause?

return sql;

Close DB Connection access public param resource return void function _close(conn_id) require_once('Parser.php');

require_once('BIFFwriter.php');

Class for generating Excel Spreadsheets author Xavier Noguer xnoguerrezebra.com package Spreadsheet_WriteExcel class Worksheet extends BIFFwriter { Constructor param string name The name of the new worksheet param integer index The index of the new worksheet param mixed activesheet The current activesheet of the workbook we belong to param mixed firstsheet The first worksheet in the workbook we belong to param mixed url_format The default format for hyperlinks param mixed parser The formula parser created for the Workbook function Worksheet(name,index,activesheet,firstsheet,url_format,parser) thisBIFFwriter(); It needs to call its parent's constructor explicitly rowmax 65536; 16384 in Excel 5 colmax 256;

strmax 255;thisname name;thisindex index;thisactivesheet activesheet;

thisfirstsheet firstsheet;this_url_format url_format;this_parser parser;thisext_sheets array();this_using_tmpfile 1;

this_filehandle;thisfileclosed 0;

thisoffset 0;thisxls_rowmax rowmax;

thisxls_colmax colmax;thisxls_strmax strmax;

thisdim_rowmin rowmax +1;thisdim_rowmax 0;

thisdim_colmin colmax +1;thisdim_colmax 0;

thiscolinfo array();this_selection array(0,0,0,0);

this_panes array();this_active_pane 3;this_frozen 0;thisselected 0;this_paper_size 0x0;this_orientation 0x1;this_header '';

this_footer '';this_hcenter 0;this_vcenter 0;

this_margin_head 0.50;this_margin_foot 0.50;this_margin_left 0.5;

this_margin_right 0.75;this_margin_top 1.00;this_margin_bottom 1.00;this_title_rowmin NULL;this_title_rowmax NULL;

this_title_colmin NULL;this_title_colmax NULL;this_print_rowmin NULL;

this_print_rowmax NULL;this_print_colmin NULL;this_print_colmax NULL;

this_print_gridlines 1;this_print_headers 0;this_fit_page 0;this_fit_width 0;this_fit_height 0;this_hbreaks array();this_vbreaks array();this_protect 0;this_password NULL;thiscol_sizes array();

thisrow_sizes array();this_zoom 100;

this_print_scale 100;this_initialize();

Open a tmp file to store the majority of the Worksheet data. If this fails, for example due to write permissions, store the data in memory. This can be slow for large files.

function _initialize() Open tmp file for storing Worksheet data fh tmpfile();

if ( fh) { Store filehandle this_filehandle fh;

else { If tmpfile() fails store data in memory this_using_tmpfile 0;

Add data to the beginning of the workbook (note the reverse order) and to the end of the workbook.

access public see Workbook:store_workbook() param array sheetnames The array of sheetnames from the Workbook this worksheet belongs to function close(sheetnames) num_sheets count(sheetnames);

Prepend in reverse order!

Prepend the sheet dimensions this_store_dimensions();

Prepend the sheet password this_store_password();

Prepend the sheet protection this_store_protect();

Prepend the page setup this_store_setup();

Prepend the bottom margin this_store_margin_bottom();

Prepend the top margin this_store_margin_top();

Prepend the right margin this_store_margin_right();

Prepend the left margin this_store_margin_left();

Prepend the page vertical centering thisstore_vcenter();

Prepend the page horizontal centering thisstore_hcenter();

Prepend the page footer thisstore_footer();

Prepend the page header thisstore_header();

Prepend the vertical page breaks this_store_vbreak();

Prepend the horizontal page breaks this_store_hbreak();

Prepend WSBOOL this_store_wsbool(); Prepend GRIDSET this_store_gridset();

Prepend PRINTGRIDLINES this_store_print_gridlines(); Prepend PRINTHEADERS this_store_print_headers(); Prepend EXTERNSHEET references for (i num_sheets; i 0; i) { sheetname sheetnames;

this_store_externsheet(sheetname); Prepend the EXTERNCOUNT of external references.this_store_externcount(num_sheets);

Prepend the COLINFO records if they exist if (!empty(thiscolinfo)){ for(i0; i count(thiscolinfo); i++) this_store_colinfo(thiscolinfo);

this_store_defcol(); Prepend the BOF record this_store_bof(0x010);

End of prepend. Read upwards from here.

Append this_store_window2();

this_store_zoom();

if(!empty(this_panes)) this_store_panes(this_panes);

this_store_selection(this_selection);

this_store_eof();

Retrieve the worksheet name. This is usefull when creating worksheets without a name.

access public return string The worksheet's name function get_name() return(thisname);

Retrieves data from memory in one chunk, or from disk in buffer sized chunks.

return string The data function get_data() buffer 4096;

Return data stored in memory if (isset(this_data)) { tmp this_data;

unset(this_data);

fh this_filehandle;

if (this_using_tmpfile) { fseek(fh, 0);

return(tmp);

Return data stored on disk if (this_using_tmpfile) { if (tmp fread(this_filehandle, buffer)) { return(tmp);

No data to return return('');

Set this worksheet as a selected worksheet, i.e. the worksheet has its tab highlighted.

access public function select() thisselected 1;

Set this worksheet as the active worksheet, i.e. the worksheet that is displayed when the workbook is opened. Also set it as selected.

access public function activate() thisselected 1;

thisactivesheet thisindex;

Set this worksheet as the first visible sheet. This is necessary when there are a large number of worksheets and the activated worksheet is not visible on the screen.

access public function set_first_sheet() thisfirstsheet thisindex;

Set the worksheet protection flag to prevent accidental modification and to hide formulas if the locked and hidden format properties have been set.

access public param string password The password to use for protecting the sheet.

function protect(password) this_protect 1;

this_password this_encode_password(password);

Set the width of a single column or a range of columns.

access public see _store_colinfo() param integer firstcol first column on the range param integer lastcol last column on the range param integer width width to set param mixed format The optional XF format to apply to the columns param integer hidden The optional hidden atribute function set_column(firstcol, lastcol, width, format 0, hidden 0) thiscolinfo array(firstcol, lastcol, width, format, hidden);

Set width to zero if column is hidden width (hidden) ? 0: width;

for(col firstcol; col lastcol; col++) { thiscol_sizes width;

Set which cell or cells are selected in a worksheet access public param integer first_row first row in the selected quadrant param integer first_column first column in the selected quadrant param integer last_row last row in the selected quadrant param integer last_column last column in the selected quadrant see _store_selection() function set_selection(first_row,first_column,last_row,last_column) this_selection array(first_row,first_column,last_row,last_column);

Set panes and mark them as frozen.

access public param array panes This is the only parameter received and is composed of the following:

0 Vertical split position, 1 Horizontal split position 2 Top row visible 3 Leftmost column visible 4 Active pane function freeze_panes(panes) this_frozen 1;

this_panes panes;

Set panes and mark them as unfrozen.

access public param array panes This is the only parameter received and is composed of the following:

0 Vertical split position, 1 Horizontal split position 2 Top row visible 3 Leftmost column visible 4 Active pane function thaw_panes(panes) this_frozen 0;

this_panes panes;

Set the page orientation as portrait.

access public function set_portrait() this_orientation 1;

Set the page orientation as landscape.

access public function set_landscape() this_orientation 0;

Set the paper type. Ex. 1 US Letter, 9 A4 access public param integer size The type of paper size to use function set_paper(size 0) this_paper_size size;

Set the page header caption and optional margin.

access public param string string The header text param float margin optional head margin in inches.

function set_header(string,margin 0.50)

if (strlen(string) 255) { carp 'Header string must be less than 255 characters';

return;

this_header string;

this_margin_head margin;

Set the page footer caption and optional margin.

access public param string string The footer text param float margin optional foot margin in inches.

function set_footer(string,margin 0.50)

if (strlen(string) 255) { carp 'Footer string must be less than 255 characters';

return;

this_footer string;

this_margin_foot margin;

Center the page horinzontally.

access public param integer center the optional value for centering. Defaults to 1 (center).

function center_horizontally(center 1) this_hcenter center;

Center the page horinzontally.

access public param integer center the optional value for centering. Defaults to 1 (center).

function center_vertically(center 1) this_vcenter center;

Set all the page margins to the same value in inches.

access public param float margin The margin to set in inches function set_margins(margin) thisset_margin_left(margin);

thisset_margin_right(margin);

thisset_margin_top(margin);

thisset_margin_bottom(margin);

Set the left and right margins to the same value in inches.

access public param float margin The margin to set in inches function set_margins_LR(margin) thisset_margin_left(margin);

thisset_margin_right(margin);

Set the top and bottom margins to the same value in inches.

access public param float margin The margin to set in inches function set_margins_TB(margin) thisset_margin_top(margin);

thisset_margin_bottom(margin);

Set the left margin in inches.

access public param float margin The margin to set in inches function set_margin_left(margin 0.75)

this_margin_left margin;

Set the right margin in inches.

access public param float margin The margin to set in inches function set_margin_right(margin 0.75)

this_margin_right margin;

Set the top margin in inches.

access public param float margin The margin to set in inches function set_margin_top(margin 1.00)

this_margin_top margin;

Set the bottom margin in inches.

access public param float margin The margin to set in inches function set_margin_bottom(margin 1.00)

this_margin_bottom margin;

Set the rows to repeat at the top of each printed page. See also the _store_name_xxxx() methods in Workbook.php access public param integer first_row First row to repeat param integer last_row Last row to repeat. Optional.

function repeat_rows(first_row, last_row NULL) this_title_rowmin first_row;

if(isset(last_row)) { Second row is optional this_title_rowmax last_row;

else { this_title_rowmax first_row;

Set the columns to repeat at the left hand side of each printed page.

See also the _store_names() methods in Workbook.php access public param integer first_col First column to repeat param integer last_col Last column to repeat. Optional.

function repeat_columns(first_col, last_col NULL) this_title_colmin first_col;

if(isset(last_col)) { Second col is optional this_title_colmax last_col;

else { this_title_colmax first_col;

Set the area of each worksheet that will be printed.

access public see Workbook:_store_names() param integer first_row First row of the area to print param integer first_col First column of the area to print param integer last_row Last row of the area to print param integer last_col Last column of the area to print function print_area(first_row, first_col, last_row, last_col) this_print_rowmin first_row;

this_print_colmin first_col;

this_print_rowmax last_row;

this_print_colmax last_col;

Set the option to hide gridlines on the printed page.

access public see _store_print_gridlines(), _store_gridset() function hide_gridlines() this_print_gridlines 0;

Set the option to print the row and column headers on the printed page.

See also the _store_print_headers() method below.

access public see _store_print_headers() param integer print Whether to print the headers or not. Defaults to 1 (print).

function print_row_col_headers(print 1) this_print_headers print;

Store the vertical and horizontal number of pages that will define the maximum area printed. It doesn't seem to work with OpenOffice.

access public param integer width Maximun width of printed area in pages param integer heigth Maximun heigth of printed area in pages see set_print_scale() function fit_to_pages(width, height) this_fit_page 1;

this_fit_width width;

this_fit_height height;

Store the horizontal page breaks on a worksheet (for printing).

The breaks represent the row after which the break is inserted.

access public param array breaks Array containing the horizontal page breaks function set_h_pagebreaks(breaks) foreach(breaks as break) { array_push(this_hbreaks,break);

Store the vertical page breaks on a worksheet (for printing).

The breaks represent the column after which the break is inserted.

access public param array breaks Array containing the vertical page breaks function set_v_pagebreaks(breaks) foreach(breaks as break) { array_push(this_vbreaks,break);

Set the worksheet zoom factor.

access public param integer scale The zoom factor function set_zoom(scale 100) Confine the scale to Excel's range if (scale 10 or scale 400) { carp "Zoom factor scale outside range: 10 zoom 400";

scale 100;

this_zoom floor(scale);

Set the scale factor for the printed page.

It turns off the option access public param integer scale The optional scale factor. Defaults to 100 function set_print_scale(scale 100) Confine the scale to Excel's range if (scale 10 or scale 400) REPLACE THIS FOR A WARNING die("Print scale scale outside range: 10 zoom 400");

scale 100;

Turn off option this_fit_page 0;

this_print_scale floor(scale);

Map to the appropriate write method acording to the token recieved.

access public param integer row The row of the cell we are writing to param integer col The column of the cell we are writing to param mixed token What we are writing param mixed format The optional format to apply to the cell function write(row, col, token, format 0) Check for a cell reference in A1 notation and substitute row and column if (_ ~ ^\D) { _ this_substitute_cellref(_);

} Match an array ref.

if (ref token eq ) { return thiswrite_row(_);

} Match number if (preg_match("^(?)(?\d|\.\d)\d(\.\d)?((?\d+))?",token)) { return thiswrite_number(row,col,token,format);

Match http or ftp URL elseif (preg_match(,token)) { return thiswrite_url(row, col, token, format);

Match mailto:

elseif (preg_match(,token)) { return thiswrite_url(row, col, token, format);

Match internal or external sheet link elseif (preg_match("^(?:in|ex)ternal:",token)) { return thiswrite_url(row, col, token, format);

Match formula elseif (preg_match(,token)) { return thiswrite_formula(row, col, token, format);

Match formula elseif (preg_match(,token)) { return thiswrite_formula(row, col, token, format);

Match blank elseif (token '') { return thiswrite_blank(row,col,format);

Default: match string else { return thiswrite_string(row,col,token,format);

Returns an index to the XF record in the workbook param mixed format The optional XF format return integer The XF record index function _XF(format) if(format ! 0)

return(formatget_xf_index());

else return(0x0F);

Internal methods Store Worksheet data in memory using the parent's class append() or to a temporary file, the default.

param string data The binary data to append function _append(data) if (this_using_tmpfile) Add CONTINUE records if necessary if (strlen(data) this_limit) { data this_add_continue(data);

fwrite(this_filehandle,data);

this_datasize + strlen(data);

else { parent:_append(data);

Substitute an Excel cell reference in A1 notation for zero based row and column values in an argument list.

Ex: (, ) is converted to (3, 0, ).

param string cell The cell reference. Or range of cells.

return array function _substitute_cellref(cell) cell strtoupper(cell);

Convert a column range: 'A:A' or 'B:G' if (preg_match("(?):(?)",cell,match)) { list(no_use, col1) this_cell_to_rowcol(match.'1'); Add a dummy row list(no_use, col2) this_cell_to_rowcol(match.'1'); Add a dummy row return(array(col1, col2));

Convert a cell range: 'A1:B7' if (preg_match("\?(?\?\d+):\?(?\?\d+)",cell,match)) { list(row1, col1) this_cell_to_rowcol(match);

list(row2, col2) this_cell_to_rowcol(match);

return(array(row1, col1, row2, col2));

Convert a cell reference: 'A1' or 'AD2000' if (preg_match("\?(?\?\d+)",cell)) { list(row1, col1) this_cell_to_rowcol(match);

return(array(row1, col1));

die("Unknown cell reference cell ");

Convert an Excel cell reference in A1 notation to a zero based row and column reference; converts C1 to (0, 2).

param string cell The cell reference.

return array containing (row, column) function _cell_to_rowcol(cell) preg_match("\?(?)\?(\d+)",cell,match);

col match;

row match;

Convert base26 column string to number chars split('', col);

expn 0;

col 0;

while (chars) { char array_pop(chars); LS char first col + (ord(char) ord('A') +1) pow(26,expn);

expn++;

Convert 1index to zeroindex row;

col;

return(array(row, col));

Based on the algorithm provided by Daniel Rentz of OpenOffice.

param string plaintext The password to be encoded in plaintext.

return string The encoded password function _encode_password(plaintext) password 0x0000;

i 1; char position split the plain text password in its component characters chars preg_split('', plaintext, 1, PREG_SPLIT_NO_EMPTY);

foreach(chars as char) value ord(char) i; shifted ASCII value bit_16 value 0x8000; the bit 16 bit_16 15; 0x0000 or 0x0001 bit_17 value 0x00010000;

bit_17 15;

value 0x7fff; first 15 bits password ^ (value | bit_16);

password ^ (value | bit_16 | bit_17);

i++;

password ^ strlen(plaintext);

password ^ 0xCE4B;

return(password);

BIFF RECORDS Write a double to the specified row and column (zero indexed).

An integer can be written as a double. Excel will display an integer. format is optional.

Returns 0: normal termination 2: row or column out of range access public param integer row Zero indexed row param integer col Zero indexed column param float num The number to write param mixed format The optional XF format function write_number(row, col, num, format 0) record 0x0203; Record identifier length 0x000E; Number of bytes to follow xf this_XF(format); The cell format Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

header pack(, record, length);

data pack(, row, col, xf);

xl_double pack(, num);

if (this_byte_order) if it's Big Endian xl_double strrev(xl_double);

this_append(header.data.xl_double);

return(0);

Write a string to the specified row and column (zero indexed).

NOTE: there is an Excel 5 defined limit of 255 characters.

format is optional.

Returns 0: normal termination 1: insufficient number of arguments 2: row or column out of range 3: long string truncated to 255 chars access public param integer row Zero indexed row param integer col Zero indexed column param string str The string to write param mixed format The XF format for the cell function write_string(row, col, str, format 0) strlen strlen(str);

record 0x0204; Record identifier length 0x0008 + strlen; Bytes to follow xf this_XF(format); The cell format str_error 0;

Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

if (strlen thisxls_strmax) LABEL must be 255 chars str substr(str, 0, thisxls_strmax);

length 0x0008 + thisxls_strmax;

strlen thisxls_strmax;

str_error 3;

header pack(, record, length);

data pack(, row, col, xf, strlen);

this_append(header.data.str);

return(str_error);

Writes a note associated with the cell given by the row and column.

NOTE records don't have a length limit.

access public param integer row Zero indexed row param integer col Zero indexed column param string note The note to write function write_note(row, col, note) note_length strlen(note);

record 0x001C; Record identifier max_length 2048; Maximun length for a NOTE record length 0x0006 + note_length; Bytes to follow Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

Length for this record is no more than 2048 + 6 length 0x0006 + min(note_length, 2048);

header pack(, record, length);

data pack(, row, col, note_length);

this_append(header.data.substr(note, 0, 2048));

for(i max_length; i note_length; i + max_length) chunk substr(note, i, max_length);

length 0x0006 + strlen(chunk);

header pack(, record, length);

data pack(, 1, 0, strlen(chunk));

this_append(header.data.chunk);

return(0);

Write a blank cell to the specified row and column (zero indexed).

A blank cell is used to specify formatting without adding a string or a number.

A blank cell without a format serves no purpose. Therefore, we don't write a BLANK record unless a format is specified. This is mainly an optimisation for the write_row() and write_col() methods.

Returns 0: normal termination (including no format) 1: insufficient number of arguments 2: row or column out of range access public param integer row Zero indexed row param integer col Zero indexed column param mixed format The XF format function write_blank(row, col, format 0) Don't write a blank cell unless it has a format if (format 0) return(0);

record 0x0201; Record identifier length 0x0006; Number of bytes to follow xf this_XF(format); The cell format Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

header pack(, record, length);

data pack(, row, col, xf);

this_append(header.data);

return 0;

Write a formula to the specified row and column (zero indexed).

The textual representation of the formula is passed to the parser in Parser.php which returns a packed binary string.

Returns 0: normal termination 2: row or column out of range access public param integer row Zero indexed row param integer col Zero indexed column param string formula The formula text string param mixed format The optional XF format function write_formula(row, col, formula, format 0) record 0x0006; Record identifier Excel normally stores the last calculated value of the formula in num.

Clearly we are not in a position to calculate this a priori. Instead we set num to zero and set the option flags in grbit to ensure automatic calculation of the formula when the file is opened.

xf this_XF(format); The cell format num 0x00; Current value of formula grbit 0x03; Option flags chn 0x0000; Must be zero Check that row and col are valid and store max and min values if (row thisxls_rowmax) return(2);

if (col thisxls_colmax) return(2);

if (row thisdim_rowmin) thisdim_rowmin row;

if (row thisdim_rowmax) thisdim_rowmax row;

if (col thisdim_colmin) thisdim_colmin col;

if (col thisdim_colmax) thisdim_colmax col;

Strip the '' or '' sign at the beginning of the formula string if (ereg(,formula)) { formula preg_replace(,,formula);

elseif(ereg(,formula)) { formula preg_replace(,,formula);

else { die("Unrecognised character for formula");

Parse the formula using the parser in Parser.php tree new Parser(this_byte_order);

this_parserparse(formula);

treeparse(formula);

formula this_parserto_reverse_polish();

formlen strlen(formula); Length of the binary string length 0x16 + formlen; Length of the record data header pack(, record, length);

data pack(, row, col, xf, num, grbit, chn, formlen);

this_append(header.data.formula);

return 0;

Write a hyperlink. This is comprised of two elements: the visible label and the invisible link. The visible label is the same as the link unless an alternative string is specified. The label is written using the write_string() method. Therefore the 255 characters string limit applies.

string and format are optional and their order is interchangeable.

The hyperlink can be to a http, ftp, mail, internal sheet, or external directory url.

Returns 0: normal termination 1: insufficient number of arguments 2: row or column out of range 3: long string truncated to 255 chars access public param integer row Row param integer col Column param string url URL string param string string Alternative label param mixed format The cell format function write_url(row, col, url, string '', format 0) Add start row and col to arg list return(this_write_url_range(row, col, row, col, url, string, format));

This is the more general form of write_url(). It allows a hyperlink to be written to a range of cells. This function also decides the type of hyperlink to be written. These are either, Web (http, ftp, mailto), Internal (Sheet1!A1) or external ('c:\temp\foo.xlsSheet1!A1').

See also write_url() above for a general description and return values.

param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string string Alternative label param mixed format The cell format function _write_url_range(row1, col1, row2, col2, url, string '', format 0) Check for internalexternal sheet links or default to web link if (preg_match('', url)) { return(this_write_url_internal(row1, col1, row2, col2, url, string, format));

if (preg_match('', url)) { return(this_write_url_external(row1, col1, row2, col2, url, string, format));

return(this_write_url_web(row1, col1, row2, col2, url, string, format));

Used to write http, ftp and mailto hyperlinks.

The link type (options) is 0x03 is the same as absolute dir ref without sheet. However it is differentiated by the unknown2 data stream.

see write_url() param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string str Alternative label param mixed format The cell format function _write_url_web(row1, col1, row2, col2, url, str, format 0) record 0x01B8; Record identifier length 0x00000; Bytes to follow if(format 0) { format this_url_format;

Write the visible label using the write_string() method.

if(str '') { str url;

str_error thiswrite_string(row1, col1, str, format);

if (str_error 2) { return(str_error);

Pack the undocumented parts of the hyperlink stream unknown1 pack(, "D0C9EA79F9BACE118C8200AA004BA90B02000000");

unknown2 pack(, "E0C9EA79F9BACE118C8200AA004BA90B");

Pack the option flags options pack(, 0x03);

Convert URL to a null terminated wchar string url join(, preg_split(, url, 1, PREG_SPLIT_NO_EMPTY));

url url.;

Pack the length of the URL url_len pack(, strlen(url));

Calculate the data length length 0x34 + strlen(url);

Pack the header data header pack(, record, length);

data pack(, row1, row2, col1, col2);

Write the packed data this_append( header. data.

unknown1. options.

unknown2. url_len. url);

return(str_error);

Used to write internal reference hyperlinks such as.

see write_url() param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string str Alternative label param mixed format The cell format function _write_url_internal(row1, col1, row2, col2, url, str, format 0) record 0x01B8; Record identifier length 0x00000; Bytes to follow if (format 0) { format this_url_format;

Strip URL type url preg_replace('s', '', url);

Write the visible label if(str '') { str url;

str_error thiswrite_string(row1, col1, str, format);

if (str_error 2) { return(str_error);

Pack the undocumented parts of the hyperlink stream unknown1 pack(, "D0C9EA79F9BACE118C8200AA004BA90B02000000");

Pack the option flags options pack(, 0x08);

Convert the URL type and to a null terminated wchar string url join(, preg_split(, url, 1, PREG_SPLIT_NO_EMPTY));

url url.;

Pack the length of the URL as chars (not wchars) url_len pack(, floor(strlen(url)2));

Calculate the data length length 0x24 + strlen(url);

Pack the header data header pack(, record, length);

data pack(, row1, row2, col1, col2);

Write the packed data this_append(header. data.

unknown1. options.

url_len. url);

return(str_error);

Write links to external directory names such as 'c:\foo.xls', c:\foo.xlsSheet1!A1', '..foo.xls'. and '..foo.xlsSheet1!A1'.

Note: Excel writes some relative links with the dir_long string. We ignore these cases for the sake of simpler code.

see write_url() param integer row1 Start row param integer col1 Start column param integer row2 End row param integer col2 End column param string url URL string param string str Alternative label param mixed format The cell format function _write_url_external(row1, col1, row2, col2, url, str, format 0) Network drives are different. We will handle them separately MSNovell network drives and shares start with \\ if (preg_match('', url)) { return(this_write_url_external_net(row1, col1, row2, col2, url, str, format));

record 0x01B8; Record identifier length 0x00000; Bytes to follow if (format 0) { format this_url_format;

Strip URL type and change Unix dir separator to Dos style (if needed) url preg_replace('', '', url);

url preg_replace('',, url);

Write the visible label if (str '') { str preg_replace('', ' ', url);

str_error thiswrite_string(row1, col1, str, format);

if (str_error 2) { return(str_error);

Determine if the link is relative or absolute:

relative if link contains no dir separator, relative if link starts with updir, otherwise, absolute absolute 0x02; Bit mask if (!preg_match('', url)) { absolute 0x00;

if (preg_match('', url)) { absolute 0x00;

Determine if the link contains a sheet reference and change some of the parameters accordingly.

Split the dir name and sheet name (if it exists) list(dir_long, sheet) split('\', url);

link_type 0x01 | absolute;

if (isset(sheet)) { link_type | 0x08;

sheet_len pack(, strlen(sheet) + 0x01);

sheet join(, split('', sheet));

sheet.;

else { sheet_len '';

sheet '';

Pack the link type link_type pack(, link_type);

Calculate the uplevel dir count e.g. (.\.\.\ 3) up_count preg_match_all(, dir_long, useless);

up_count pack(, up_count);

Store the short dos dir name (null terminated) dir_short preg_replace('\.\.\\', '', dir_long).;

Store the long dir name as a wchar string (nonnull terminated) dir_long join(, split('', dir_long));

dir_long dir_long.;

Pack the lengths of the dir strings dir_short_len pack(, strlen(dir_short) );

dir_long_len pack(, strlen(dir_long) );

stream_len pack(, strlen(dir_long) + 0x06);

Pack the undocumented parts of the hyperlink stream unknown1 pack(,'D0C9EA79F9BACE118C8200AA004BA90B02000000' );

unknown2 pack(,'0303000000000000C000000000000046' );

unknown3 pack(,'FFFFADDE000000000000000000000000000000000000000');

unknown4 pack(, 0x03 );

Pack the main data stream data pack(, row1, row2, col1, col2).

unknown1.

link_type.

unknown2.

up_count.

dir_short_len.

dir_short.

unknown3.

stream_len.

dir_long_len.

unknown4.

dir_long.

sheet_len.

sheet;

Pack the header data length strlen(data);

header pack(, record, length);

Write the packed data this_append(header. data);

return(str_error);

write_url_xxx(row1, col1, row2, col2, url, string, format) Write links to external MSNovell network drives and shares such as 'NETWORKsharefoo.xls' and 'NETWORKsharefoo.xlsSheet1!A1'.

See also write_url() above for a general description and return values.

sub _write_url_external_net { my this shift;

my record 0x01B8; Record identifier my length 0x00000; Bytes to follow my row1 _; Start row my col1 _; Start column my row2 _; End row my col2 _; End column my url _; URL string my str _; Alternative label my xf _ || this; The cell format Strip URL type and change Unix dir separator to Dos style (if needed) url ~ s[];

url ~ s[\\]g;

Write the visible label (str url) ~ s[ ] unless defined str;

my str_error thiswrite_string(row1, col1, str, xf);

return str_error if str_error 2;

Determine if the link contains a sheet reference and change some of the parameters accordingly.

Split the dir name and sheet name (if it exists) my (dir_long, sheet) split \, url;

my link_type 0x0103; Always absolute my sheet_len;

if (defined sheet) { link_type | 0x08;

sheet_len pack(, length(sheet) + 0x01);

sheet join(, split('', sheet));

sheet.;

else { sheet_len '';

sheet '';

Pack the link type link_type pack(, link_type);

Make the string null terminated dir_long dir_long.;

Pack the lengths of the dir string my dir_long_len pack(, length dir_long);

Store the long dir name as a wchar string (nonnull terminated) dir_long join(, split('', dir_long));

dir_long dir_long.;

Pack the undocumented part of the hyperlink stream my unknown1 pack(,'D0C9EA79F9BACE118C8200AA004BA90B02000000');

Pack the main data stream my data pack(, row1, row2, col1, col2).

unknown1.link_type.

dir_long_len.dir_long.sheet_len.

sheet;Pack the header data length length data;

my header pack(, record, length);

Write the packed data this_append( header, data);

return str_error;

} This method is used to set the height and XF format for a row.

Writes the BIFF record ROW.

access public param integer row The row to set param integer height Height we are giving to the row.

Use NULL to set XF without setting height param mixed format XF format we are giving to the row function set_row(row, height, format 0) record 0x0208; Record identifier length 0x0010; Number of bytes to follow colMic 0x0000; First defined column colMac 0x0000; Last defined column irwMac 0x0000; Used by Excel to optimise loading reserved 0x0000; Reserved grbit 0x01C0; Option flags. (monkey) see 1 do ixfe this_XF(format); XF index Use set_row(row, NULL, XF) to set XF without setting height if (height ! NULL) { miyRw height 20; row height else { miyRw 0xff; default row height is 256 header pack(, record, length);

data pack(, row, colMic, colMac, miyRw, irwMac,reserved, grbit, ixfe);

this_append(header.data);

Writes Excel DIMENSIONS to define the area in which there is data.

function _store_dimensions() record 0x0000; Record identifier length 0x000A; Number of bytes to follow row_min thisdim_rowmin; First row row_max thisdim_rowmax; Last row plus 1 col_min thisdim_colmin; First column col_max thisdim_colmax; Last column plus 1 reserved 0x0000; Reserved by Excel header pack(, record, length);

data pack(, row_min, row_max, col_min, col_max, reserved);

this_prepend(header.data);

Write BIFF record Window2.

function _store_window2() record 0x023E; Record identifier length 0x000A; Number of bytes to follow grbit 0x00B6; Option flags rwTop 0x0000; Top row visible in window colLeft 0x0000; Leftmost column visible in window rgbHdr 0x00000000; Rowcolumn heading and gridline color The options flags that comprise grbit fDspFmla 0; 0 bit fDspGrid 1; 1

fDspRwCol 1; 2

fFrozen this_frozen; 3

fDspZeros 1; 4

fDefaultHdr 1; 5

fArabic 0; 6

fDspGuts 1; 7

fFrozenNoSplit 0; 0 bit fSelected thisselected; 1

fPaged 1; 2

grbit fDspFmla;

grbit | fDspGrid 1;

grbit | fDspRwCol 2;

grbit | fFrozen 3;

grbit | fDspZeros 4;

grbit | fDefaultHdr 5;

grbit | fArabic 6;

grbit | fDspGuts 7;

grbit | fFrozenNoSplit 8;

grbit | fSelected 9;

grbit | fPaged 10;

header pack(, record, length);

data pack(, grbit, rwTop, colLeft, rgbHdr);

this_append(header.data);

Write BIFF record DEFCOLWIDTH if COLINFO records are in use.

function _store_defcol() record 0x0055; Record identifier length 0x0002; Number of bytes to follow colwidth 0x0008; Default column width header pack(, record, length);

data pack(, colwidth);

this_prepend(header.data);

Write BIFF record COLINFO to define column widths Note: The SDK says the record length is 0x0B but Excel writes a 0x0C length record.

param array col_array This is the only parameter received and is composed of the following:

0 First formatted column, 1 Last formatted column, 2 Col width (8.43 is Excel default), 3 The optional XF format of the column, 4 Option flags.

function _store_colinfo(col_array) if(isset(col_array)) { colFirst col_array;

if(isset(col_array)) { colLast col_array;

if(isset(col_array)) { coldx col_array;

else { coldx 8.43;

if(isset(col_array)) { format col_array;

else { format 0;

if(isset(col_array)) { grbit col_array;

else { grbit 0;

record 0x007D; Record identifier length 0x000B; Number of bytes to follow coldx + 0.72; Fudge. Excel subtracts 0.72 !?

coldx 256; Convert to units of 1256 of a char ixfe this_XF(format);

reserved 0x00; Reserved header pack(, record, length);

data pack(, colFirst, colLast, coldx, ixfe, grbit, reserved);

this_prepend(header.data);

Write BIFF record SELECTION.

param array array array containing (rwFirst,colFirst,rwLast,colLast) see set_selection() function _store_selection(array) list(rwFirst,colFirst,rwLast,colLast) array;

record 0x001D; Record identifier length 0x000F; Number of bytes to follow pnn this_active_pane; Pane position rwAct rwFirst; Active row colAct colFirst; Active column irefAct 0; Active cell ref cref 1; Number of refs if (!isset(rwLast)) { rwLast rwFirst; Last row in reference if (!isset(colLast)) { colLast colFirst; Last col in reference Swap last rowcol for first rowcol as necessary if (rwFirst rwLast) list(rwFirst, rwLast) array(rwLast, rwFirst);

if (colFirst colLast) list(colFirst, colLast) array(colLast, colFirst);

header pack(, record, length);

data pack(, pnn, rwAct, colAct, irefAct, cref, rwFirst, rwLast, colFirst, colLast);

this_append(header.data);

Write BIFF record EXTERNCOUNT to indicate the number of external sheet references in a worksheet.

Excel only stores references to external sheets that are used in formulas.

For simplicity we store references to all the sheets in the workbook regardless of whether they are used or not. This reduces the overall complexity and eliminates the need for a two way dialogue between the formula parser the worksheet objects.

param integer count The number of external sheet references in this worksheet function _store_externcount(count) record 0x0016; Record identifier length 0x0002; Number of bytes to follow header pack(, record, length);

data pack(, count);

this_prepend(header.data);

Writes the Excel BIFF EXTERNSHEET record. These references are used by formulas. A formula references a sheet name via an index. Since we store a reference to all of the external worksheets the EXTERNSHEET index is the same as the worksheet index.

param string sheetname The name of a external worksheet function _store_externsheet(sheetname) record 0x0017; Record identifier References to the current sheet are encoded differently to references to external sheets.

if (thisname sheetname) { sheetname '';

length 0x02; The following 2 bytes cch 1; The following byte rgch 0x02; Self reference else { length 0x02 + strlen(sheetname);

cch strlen(sheetname);

rgch 0x03; Reference to a sheet in the current workbook header pack(, record, length);

data pack(, cch, rgch);

this_prepend(header.data.sheetname);

Writes the Excel BIFF PANE record.

The panes can either be frozen or thawed (unfrozen).

Frozen panes are specified in terms of an integer number of rows and columns.

Thawed panes are specified in terms of Excel's units for rows and columns.

param array panes This is the only parameter received and is composed of the following:

0 Vertical split position, 1 Horizontal split position 2 Top row visible 3 Leftmost column visible 4 Active pane function _store_panes(panes) y panes;

x panes;

rwTop panes;

colLeft panes;

if(count(panes) 4) { if Active pane was received pnnAct panes;

else { pnnAct NULL;

record 0x0041; Record identifier length 0x000A; Number of bytes to follow Code specific to frozen or thawed panes.

if (this_frozen) { Set default values for rwTop and colLeft if(!isset(rwTop)) { rwTop y;

if(!isset(colLeft)) { colLeft x;

else { Set default values for rwTop and colLeft if(!isset(rwTop)) { rwTop 0;

if(!isset(colLeft)) { colLeft 0;

Convert Excel's row and column units to the internal units.

The default row height is 12.75

The default column width is 8.43

The following slope and intersection values were interpolated.

y 20y + 255;

x 113.879x + 390;

Determine which pane should be active. There is also the undocumented option to override this should it be necessary: may be removed later.

if (!isset(pnnAct)) if (x ! 0 and y ! 0)

pnnAct 0; Bottom right if (x ! 0 and y 0) pnnAct 1; Top right if (x 0 and y ! 0)

pnnAct 2; Bottom left if (x 0 and y 0) pnnAct 3; Top left this_active_pane pnnAct; Used in _store_selection header pack(, record, length);

data pack(, x, y, rwTop, colLeft, pnnAct);

this_append(header.data);

Store the page setup SETUP BIFF record.

function _store_setup() record 0x00A1; Record identifier length 0x0022; Number of bytes to follow iPaperSize this_paper_size; Paper size iScale this_print_scale; Print scaling factor iPageStart 0x01; Starting page number iFitWidth this_fit_width; Fit to number of pages wide iFitHeight this_fit_height; Fit to number of pages high grbit 0x00; Option flags iRes 0x0258; Print resolution iVRes 0x0258; Vertical print resolution numHdr this_margin_head; Header Margin numFtr this_margin_foot; Footer Margin iCopies 0x01; Number of copies fLeftToRight 0x0; Print over then down fLandscape this_orientation; Page orientation fNoPls 0x0; Setup not read from printer fNoColor 0x0; Print black and white fDraft 0x0; Print draft quality fNotes 0x0; Print notes fNoOrient 0x0; Orientation not set fUsePage 0x0; Use custom starting page grbit fLeftToRight;

grbit | fLandscape 1;

grbit | fNoPls 2;

grbit | fNoColor 3;

grbit | fDraft 4;

grbit | fNotes 5;

grbit | fNoOrient 6;

grbit | fUsePage 7;

numHdr pack(, numHdr);

numFtr pack(, numFtr);

if (this_byte_order) if it's Big Endian numHdr strrev(numHdr);

numFtr strrev(numFtr);

header pack(, record, length);

data1 pack(, iPaperSize, iScale, iPageStart, iFitWidth, iFitHeight, grbit, iRes, iVRes);

data2 numHdr.numFtr;

data3 pack(, iCopies);

this_prepend(header.data1.data2.data3);

Store the header caption BIFF record.

function store_header() record 0x0014; Record identifier str this_header; header string cch strlen(str); Length of header string length 1 + cch; Bytes to follow header pack(, record, length);

data pack(, cch);

this_append(header.data.str);

Store the footer caption BIFF record.

function store_footer() record 0x0015; Record identifier str this_footer; Footer string cch strlen(str); Length of footer string length 1 + cch; Bytes to follow header pack(, record, length);

data pack(, cch);

this_append(header.data.str);

Store the horizontal centering HCENTER BIFF record.

function store_hcenter() record 0x0083; Record identifier length 0x0002; Bytes to follow fHCenter this_hcenter; Horizontal centering header pack(, record, length);

data pack(, fHCenter);

this_append(header.data);

Store the vertical centering VCENTER BIFF record.

function store_vcenter() record 0x0084; Record identifier length 0x0002; Bytes to follow fVCenter this_vcenter; Horizontal centering header pack(, record, length);

data pack(, fVCenter);

this_append(header.data);

Store the LEFTMARGIN BIFF record.

function _store_margin_left() record 0x0026; Record identifier length 0x0008; Bytes to follow margin this_margin_left; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

Store the RIGHTMARGIN BIFF record.

function _store_margin_right() record 0x0027; Record identifier length 0x0008; Bytes to follow margin this_margin_right; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

Store the TOPMARGIN BIFF record.

function _store_margin_top() record 0x0028; Record identifier length 0x0008; Bytes to follow margin this_margin_top; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

Store the BOTTOMMARGIN BIFF record.

function _store_margin_bottom() record 0x0029; Record identifier length 0x0008; Bytes to follow margin this_margin_bottom; Margin in inches header pack(, record, length);

data pack(, margin);

if (this_byte_order) if it's Big Endian { data strrev(data);

this_append(header.data);

This is an Excel972000 method. It is required to perform more complicated merging than the normal set_align('merge'). It merges the area given by its arguments.

access public param integer first_row First row of the area to merge param integer first_col First column of the area to merge param integer last_row Last row of the area to merge param integer last_col Last column of the area to merge function merge_cells(first_row, first_col, last_row, last_col) record 0x00E5; Record identifier length 0x000A; Bytes to follow cref 1; Number of refs Swap last rowcol for first rowcol as necessary if (first_row last_row) { list(first_row, last_row) array(last_row, first_row);

if (first_col last_col) { list(first_col, last_col) array(last_col, first_col);

header pack(, record, length);

data pack(, cref, first_row, last_row, first_col, last_col);

this_append(header.data);

Write the PRINTHEADERS BIFF record.

function _store_print_headers() record 0x002a; Record identifier length 0x0002; Bytes to follow fPrintRwCol this_print_headers; Boolean flag header pack(, record, length);

data pack(, fPrintRwCol);

this_prepend(header.data);

Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the GRIDSET record.

function _store_print_gridlines() record 0x002b; Record identifier length 0x0002; Bytes to follow fPrintGrid this_print_gridlines; Boolean flag header pack(, record, length);

data pack(, fPrintGrid);

this_prepend(header.data);

Write the GRIDSET BIFF record. Must be used in conjunction with the PRINTGRIDLINES record.

function _store_gridset() record 0x0082; Record identifier length 0x0002; Bytes to follow fGridSet !(this_print_gridlines); Boolean flag header pack(, record, length);

data pack(, fGridSet);

this_prepend(header.data);

Write the WSBOOL BIFF record, mainly for fittopage. Used in conjunction with the SETUP record.

function _store_wsbool() record 0x0081; Record identifier length 0x0002; Bytes to follow The only option that is of interest is the flag for fit to page. So we set all the options in one go.

if (this_fit_page) { grbit 0x05c1;

else { grbit 0x04c1;

header pack(, record, length);

data pack(, grbit);

this_prepend(header.data);

Write the HORIZONTALPAGEBREAKS BIFF record.

function _store_hbreak() Return if the user hasn't specified pagebreaks if(empty(this_hbreaks)) { return;

Sort and filter array of page breaks breaks this_hbreaks;

sort(breaks,SORT_NUMERIC);

if(breaks 0) { don't use first break if it's 0 array_shift(breaks);

record 0x001b; Record identifier cbrk count(breaks); Number of page breaks length (cbrk + 1) 2; Bytes to follow header pack(, record, length);

data pack(, cbrk);

Append each page break foreach(breaks as break) { data. pack(, break);

this_prepend(header.data);

Write the VERTICALPAGEBREAKS BIFF record.

function _store_vbreak() Return if the user hasn't specified pagebreaks if(empty(this_vbreaks)) { return;

1000 vertical pagebreaks appears to be an internal Excel 5 limit.

It is slightly higher in Excel 97200, approx. 1026

breaks array_slice(this_vbreaks,0,1000);

Sort and filter array of page breaks sort(breaks,SORT_NUMERIC);

if(breaks 0) { don't use first break if it's 0 array_shift(breaks);

record 0x001a; Record identifier cbrk count(breaks); Number of page breaks length (cbrk + 1) 2; Bytes to follow header pack(, record, length);

data pack(, cbrk);

Append each page break foreach (breaks as break) { data. pack(, break);

this_prepend(header.data);

Set the Biff PROTECT record to indicate that the worksheet is protected.

function _store_protect() Exit unless sheet protection has been specified if(this_protect 0) { return;

record 0x0012; Record identifier length 0x0002; Bytes to follow fLock this_protect; Worksheet is protected header pack(, record, length);

data pack(, fLock);

this_prepend(header.data);

Write the worksheet PASSWORD record.

function _store_password() Exit unless sheet protection and password have been specified if((this_protect 0) or (!isset(this_password))) { return;

record 0x0013; Record identifier length 0x0002; Bytes to follow wPassword this_password; Encoded password header pack(, record, length);

data pack(, wPassword);

this_prepend(header.data);

Insert a 24bit bitmap image in a worksheet. The main record required is IMDATA but it must be proceeded by a OBJ record to define its position.

access public param integer row The row we are going to insert the bitmap into param integer col The column we are going to insert the bitmap into param string bitmap The bitmap filename param integer x The horizontal position (offset) of the image inside the cell.

param integer y The vertical position (offset) of the image inside the cell.

param integer scale_x The horizontal scale param integer scale_y The vertical scale function insert_bitmap(row, col, bitmap, x 0, y 0, scale_x 1, scale_y 1) list(width, height, size, data) this_process_bitmap(bitmap);

Scale the frame of the image.

width scale_x;

height scale_y;

Calculate the vertices of the image and write the OBJ record this_position_image(col, row, x, y, width, height);

Write the IMDATA record to store the bitmap data record 0x007f;

length 8 + size;

cf 0x09;

env 0x01;

lcb size;

header pack(, record, length, cf, env, lcb);

this_append(header.data);

Calculate the vertices that define the position of the image as required by the OBJ record.

+++

| A | B | ++++ | |(x1,y1) | | | 1 |(A1)._______|______ | | | | | | | | | | | ++| BITMAP |+ | | | | | | 2 | |______________. | | | | (B2)| | | | (x2,y2)| + +++ Example of a bitmap that covers some of the area from cell A1 to cell B2.

Based on the width and height of the bitmap we need to calculate 8 vars:

col_start, row_start, col_end, row_end, x1, y1, x2, y2.

The width and height of the cells are also variable and have to be taken into account.

The values of col_start and row_start are passed in from the calling function. The values of col_end and row_end are calculated by subtracting the width and height of the bitmap from the width and height of the underlying cells.

The vertices are expressed as a percentage of the underlying cell width as follows (rhs values are in pixels):

x1 X W 1024 y1 Y H 256 x2 (X1) W 1024 y2 (Y1) H 256 Where: X is distance from the left side of the underlying cell Y is distance from the top of the underlying cell W is the width of the cell H is the height of the cell note the SDK incorrectly states that the height should be expressed as a percentage of 1024.

param integer col_start Col containing upper left corner of object param integer row_start Row containing top left corner of object param integer x1 Distance to left side of object param integer y1 Distance to top of object param integer width Width of image frame param integer height Height of image frame function _position_image(col_start, row_start, x1, y1, width, height) Initialise end cell to the same as the start cell col_end col_start; Col containing lower right corner of object row_end row_start; Row containing bottom right corner of object Zero the specified offset if greater than the cell dimensions if (x1 thissize_col(col_start)) x1 0;

if (y1 thissize_row(row_start)) y1 0;

width width + x1 1;

height height + y1 1;

Subtract the underlying cell widths to find the end cell of the image while (width thissize_col(col_end)) { width thissize_col(col_end);

col_end++;

Subtract the underlying cell heights to find the end cell of the image while (height thissize_row(row_end)) { height thissize_row(row_end);

row_end++;

Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell with zero eight or width.

if (thissize_col(col_start) 0) return;

if (thissize_col(col_end) 0) return;

if (thissize_row(row_start) 0) return;

if (thissize_row(row_end) 0) return;

Convert the pixel values to the percentage value expected by Excel x1 x1 thissize_col(col_start) 1024;

y1 y1 thissize_row(row_start) 256;

x2 width thissize_col(col_end) 1024; Distance to right side of object y2 height thissize_row(row_end) 256; Distance to bottom of object this_store_obj_picture( col_start, x1, row_start, y1, col_end, x2, row_end, y2 );

Convert the width of a cell from user's units to pixels. By interpolation the relationship is: y 7x +5. If the width hasn't been set by the user we use the default value. If the col is hidden we use a value of zero.

param integer col The column return integer The width in pixels function size_col(col) Look up the cell value to see if it has been changed if (isset(thiscol_sizes)) { if (thiscol_sizes 0) { return(0);

else { return(floor(7 thiscol_sizes + 5));

else { return(64);

Convert the height of a cell from user's units to pixels. By interpolation the relationship is: y 43x. If the height hasn't been set by the user we use the default value. If the row is hidden we use a value of zero. (Not possible to hide row yet).

param integer row The row return integer The width in pixels function size_row(row) Look up the cell value to see if it has been changed if (isset(thisrow_sizes)) { if (thisrow_sizes 0) { return(0);

else { return(floor(43 thisrow_sizes));

else { return(17);

Store the OBJ record that precedes an IMDATA record. This could be generalise to support other Excel objects.

param integer colL Column containing upper left corner of object param integer dxL Distance from left side of cell param integer rwT Row containing top left corner of object param integer dyT Distance from top of cell param integer colR Column containing lower right corner of object param integer dxR Distance from right of cell param integer rwB Row containing bottom right corner of object param integer dyB Distance from bottom of cell function _store_obj_picture(colL,dxL,rwT,dyT,colR,dxR,rwB,dyB) record 0x005d; Record identifier length 0x003c; Bytes to follow cObj 0x0001; Count of objects in file (set to 1) OT 0x0008; Object type. 8 Picture id 0x0001; Object ID grbit 0x0614; Option flags cbMacro 0x0000; Length of FMLA structure Reserved1 0x0000; Reserved Reserved2 0x0000; Reserved icvBack 0x09; Background colour icvFore 0x09; Foreground colour fls 0x00; Fill pattern fAuto 0x00; Automatic fill icv 0x08; Line colour lns 0xff; Line style lnw 0x01; Line weight fAutoB 0x00; Automatic border frs 0x0000; Frame style cf 0x0009; Image format, 9 bitmap Reserved3 0x0000; Reserved cbPictFmla 0x0000; Length of FMLA structure Reserved4 0x0000; Reserved grbit2 0x0001; Option flags Reserved5 0x0000; Reserved header pack(, record, length);

data pack(, cObj);

data. pack(, OT);

data. pack(, id);

data. pack(, grbit);

data. pack(, colL);

data. pack(, dxL);

data. pack(, rwT);

data. pack(, dyT);

data. pack(, colR);

data. pack(, dxR);

data. pack(, rwB);

data. pack(, dyB);

data. pack(, cbMacro);

data. pack(, Reserved1);

data. pack(, Reserved2);

data. pack(, icvBack);

data. pack(, icvFore);

data. pack(, fls);

data. pack(, fAuto);

data. pack(, icv);

data. pack(, lns);

data. pack(, lnw);

data. pack(, fAutoB);

data. pack(, frs);

data. pack(, cf);

data. pack(, Reserved3);

data. pack(, cbPictFmla);

data. pack(, Reserved4);

data. pack(, grbit2);

data. pack(, Reserved5);

this_append(header.data);

Convert a 24 bit bitmap into the modified internal format used by Windows.

This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the MSDN library.

param string bitmap The bitmap to process return array Array with data and properties of the bitmap function _process_bitmap(bitmap) Open file.

bmp_fd fopen(bitmap,);

if (!bmp_fd) { die("Couldn't import bitmap");

Slurp the file into a string.

data fread(bmp_fd, filesize(bitmap));

Check that the file is big enough to be a bitmap.

if (strlen(data) 0x36) { die("bitmap doesn't contain enough data.\n");

The first 2 bytes are used to identify the bitmap.

identity unpack(, data);

if (identity ! ) { die("bitmap doesn't appear to be a valid bitmap image.\n");

Remove bitmap data: ID.

data substr(data, 2);

Read and remove the bitmap size. This is more reliable than reading the data size at offset 0x22.

size_array unpack(, substr(data, 0, 4));

size size_array;

data substr(data, 4);

size 0x36; Subtract size of bitmap header.

size + 0x0C; Add size of BIFF header.

Remove bitmap data: reserved, offset, header length.

data substr(data, 12);

Read and remove the bitmap width and height. Verify the sizes.

width_and_height unpack(, substr(data, 0, 8));

width width_and_height;

height width_and_height;

data substr(data, 8);

if (width 0xFFFF) { die("bitmap: largest image width supported is 65k.\n");

if (height 0xFFFF) { die("bitmap: largest image height supported is 65k.\n");

Read and remove the bitmap planes and bpp data. Verify them.

planes_and_bitcount unpack(, substr(data, 0, 4));

data substr(data, 4);

if (planes_and_bitcount ! 24) { Bitcount die("bitmap isn't a 24bit true color bitmap.\n");

if (planes_and_bitcount ! 1) { die("bitmap: only 1 plane supported in bitmap image.\n");

Read and remove the bitmap compression. Verify compression.

compression unpack(, substr(data, 0, 4));

data substr(data, 4);

compression 0;

if (compression ! 0) { die("bitmap: compression not supported in bitmap image.\n");

Remove bitmap data: data size, hres, vres, colours, imp. colours.

data substr(data, 20);

Add the BITMAPCOREHEADER data header pack(, 0x000c, width, height, 0x01, 0x18);

data header. data;

return (array(width, height, size, data));

Store the window zoom factor. This should be a reduced fraction but for simplicity we will store all fractions with a numerator of 100.

function _store_zoom() If scale is 100 we don't need to write a record if (this_zoom 100) { return;

record 0x00A0; Record identifier length 0x0004; Bytes to follow header pack(, record, length);

data pack(, this_zoom, 100);

this_append(header.data);