bash_sync_perms.php 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420
  1. <?php
  2. /**
  3. * by plabudda 2013-10-09:
  4. *
  5. * 1. install:
  6. * - create *.plist file:
  7. * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
  8. * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
  9. * - load by launchctl:
  10. * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  11. *
  12. * 2. uninstall:
  13. * - unload from launchctl:
  14. * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  15. *
  16. * 3. debug:
  17. * - debug by www:
  18. * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
  19. * - more verbose debug:
  20. * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
  21. * - task:
  22. * /SE/se-dev-pl/bash_sync_perms.php?task=task
  23. * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
  24. * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
  25. * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
  26. *
  27. *
  28. * 4. Sync users: `ADMIN_USERS`.`A_STATUS` - OFF - manual sync from users table (groups from CRM_LISTA_ZASOBOW)
  29. * 'WAITING' - Kandydaci
  30. * 'NORMAL' - Aktywni pracownicy
  31. * 'DELETED' - Wyłączone konta
  32. * 'OFF_SOFT' - ?
  33. * 'OFF_HARD' - ?
  34. *
  35. * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
  36. * robienie katalogow dla korespondencji przy migracji na nowy typ pism
  37. #read PASSWORD
  38. #for a in `echo "select concat(ID,';---;',K_OD_KOGO,K_ZAWARTOS) from IN7_DZIENNIK_KORESP" |mysql -p$PASSWORD -uroot -Damssystem -h127.0.0.1 | sed 's/[^a-zA-Z0-9;-]/_/g' |sed 's/;---;/\./g' ` ;
  39. #do
  40. #echo mkdir $a
  41. #mkdir $a
  42. #done
  43. *do wywolania w katalogach IN/OUT:
  44. # cd IN
  45. # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
  46. *
  47. *
  48. *
  49. * DONE: koresp format: PISMA/ID/...
  50. * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
  51. * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
  52. * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogów}
  53. * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
  54. * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
  55. *
  56. *
  57. * DONE: Trigger po update/insert Koresp po aktualizacji permów plików projektu
  58. *
  59. * 5. Sync custom tables
  60. * TEST 2014-10-27: # php /Users/plabudda/rsync-dev/SE/bash_sync_perms.php biuro.biall-net.pl SyncPermsCustomTables
  61. * 5.1 Table list in CRM_CONFIG(key=_SYNC_TABLE_FILE_PERMS__TablesList)
  62. * table must be defined in .cnf--folders-{domain}.ini.php as section [{tblName}_COLUMN]
  63. * table must have fields: ID, L_APPOITMENT_USER, A_ADM_COMPANY, A_CLASSIFIED @see generateTasksNewRecords
  64. */
  65. ini_set('max_execution_time', 300);
  66. ini_set('memory_limit', '512M');
  67. define('DS', DIRECTORY_SEPARATOR);
  68. define('APP_PATH_ROOT', dirname(__FILE__));
  69. define('APP_PATH_WWW', dirname(__FILE__));
  70. define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
  71. // set ini to log errors into error log file
  72. ini_set('display_startup_errors', '0');
  73. ini_set('log_errors', '1');
  74. ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
  75. require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
  76. Lib::loadClass('V');
  77. Lib::loadClass('Config');
  78. Lib::loadClass('DB');
  79. Lib::loadClass('User');
  80. Lib::loadClass('FoldersConfig');
  81. Lib::loadClass('FileUploader');
  82. if (isset($_SERVER["argv"][1])) {
  83. $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
  84. }
  85. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
  86. $info = array();
  87. $info['max_execution_time'] = ini_get('max_execution_time');
  88. $info['memory_limit'] = ini_get('memory_limit');
  89. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  90. ini_set('max_execution_time', 300);
  91. ini_set('memory_limit', '512M');
  92. $info = array();
  93. $info['max_execution_time'] = ini_get('max_execution_time');
  94. $info['memory_limit'] = ini_get('memory_limit');
  95. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  96. }
  97. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
  98. SyncPerms::run(null, null, 'users', null);
  99. }
  100. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
  101. SyncPerms::run(null, null, 'usersAll', null);
  102. }
  103. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
  104. SyncPerms::run(null, null, 'nextTask', null);
  105. }
  106. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
  107. SyncPerms::run(null, null, 'newFiles', null);
  108. }
  109. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
  110. $cmd = " ls -Rlea . ";
  111. exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
  112. //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 {file_name}";
  113. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
  114. $filesWithPermsTree = array();
  115. $lastName = '';
  116. $folderParent = '';
  117. foreach ($filesWithPerms as $line) {
  118. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  119. $fileParts = array();
  120. $filePartsArr = explode(' ', $line);
  121. $lastInd = 0;
  122. foreach ($filePartsArr as $vPart) {
  123. if ($lastInd > 7) {// file name
  124. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  125. $lastInd++;
  126. }
  127. else if (!empty($vPart) || $vPart === '0') {
  128. $fileParts[] = $vPart;
  129. $lastInd++;
  130. }
  131. }
  132. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  133. $lastName = '..';
  134. continue;
  135. }
  136. $file = new stdClass();
  137. if (!isset($fileParts[8])) {
  138. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  139. //continue;
  140. } else {
  141. // fix file name from bad chars
  142. // [8] => CV_Kowalski Mariusz`.pdf
  143. // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  144. // [11-Oct-2013 21:00:28 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2013-02-26_harmonogram_EDORADCA_Aktualny/-$harmonogram 01.2013.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  145. // [11-Oct-2013 21:00:27 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2012-04-19_oferta_gpon_sprint_po_poprawkach/-$Wycena GPON 2012 Biall-Net_spr v1.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  146. // [11-Oct-2013 20:56:25 UTC] PHP Notice: Error-cmd: chmod +a "user:prejsi allow write,append,writeattr,writeextattr,writesecurity,chown,read,execute,readattr,readextattr,readsecurity" "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1695.Projekt_glowny_dzialu_rozwoju_biznesu_oraz_dystrybucji_informacji/HANDLOWY/HANDLOWY_2012/OTOMIN/-$Otomin.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1517
  147. //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
  148. //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
  149. }
  150. echo'<pre style="max-height:230px;overflow:auto;border:1px solid red;text-align:left;">line/$fileParts/$filePartsArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($line, $fileParts, $filePartsArr));echo'</pre>';
  151. $file->name = end($fileParts);
  152. $file->path = array();
  153. if ($folderParent) $file->path[] = $folderParent;
  154. $file->path[] = end($fileParts);
  155. $file->path = implode('/', $file->path);
  156. //$file->owner = $fileParts[2];
  157. //$file->group = $fileParts[3];
  158. //$file->perms = $fileParts[0];
  159. $file->isDir = (substr($line, 0, 1) == 'd');
  160. $file->permsExt = array();
  161. $filesWithPermsTree[$file->name] = $file;
  162. $lastName = $file;
  163. }
  164. else if (substr($line, 0, 1) == ' ') {// extended perm line
  165. if ($lastName == '..') {
  166. continue;
  167. }
  168. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  169. }
  170. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  171. $folderParent = substr($line, 2, -1);
  172. }
  173. else if (substr($line, 0, 5) == 'total') {
  174. continue;
  175. }
  176. else if (empty($line)) {
  177. $folderParent = '';
  178. continue;
  179. }
  180. }
  181. echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
  182. }
  183. else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
  184. SyncPerms::run(null, null);
  185. }
  186. else {
  187. die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
  188. }
  189. if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
  190. $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
  191. $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
  192. SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  193. }
  194. class SyncPerms {
  195. public static function installTable() {
  196. $db = DB::getDB();
  197. if (!$db) die("DB Error: No DB! L." . __LINE__);
  198. $sql = "
  199. CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
  200. `ID` int(11) NOT NULL AUTO_INCREMENT,
  201. `ID_PROJECT` int(11) NOT NULL,
  202. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  203. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  204. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  205. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  206. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  207. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  208. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  209. PRIMARY KEY (`ID`),
  210. UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
  211. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  212. ";
  213. $db->query($sql);
  214. $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
  215. $db->query($sql);
  216. $sql = "
  217. CREATE TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
  218. FOR EACH ROW BEGIN
  219. IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
  220. update `_SYNC_FILE_PERMS` as s set
  221. s.`A_SYNCHRONIZED`=0
  222. where
  223. s.`ID_PROJECT`=NEW.`ID_PROJECT`
  224. or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
  225. END IF;
  226. END
  227. ";
  228. $db->query($sql);
  229. $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
  230. $db->query($sql);
  231. $sql = "
  232. CREATE TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
  233. FOR EACH ROW BEGIN
  234. IF NEW.`ID_PROJECT` > 0 THEN
  235. update `_SYNC_FILE_PERMS` as s set
  236. s.`A_SYNCHRONIZED`=0
  237. where
  238. s.`ID_PROJECT`=NEW.`ID_PROJECT`;
  239. END IF;
  240. END
  241. ";
  242. $db->query($sql);
  243. if (V::get('DBG', '', $_GET, 'int') > 0) {
  244. if ($db->has_errors()) {
  245. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB errors (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
  246. }
  247. }
  248. }
  249. public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
  250. if ($arg2 == 'addToLaunchctl') {
  251. system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  252. <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
  253. <plist version=\"1.0\">
  254. <dict>
  255. <key>Disabled</key>
  256. <false/>
  257. <key>Label</key>
  258. <string>pl.biallnet.sync_perms.php</string>
  259. <key>UserName</key>
  260. <string>root</string>
  261. <key>ProgramArguments</key>
  262. <array>
  263. <string>php</string>
  264. <string>{$_SERVER["argv"][0]}</string>
  265. <string>{$_SERVER["argv"][1]}</string>
  266. </array>
  267. <key>StartInterval</key>
  268. <integer>60</integer>
  269. </dict>
  270. </plist>
  271. \" > /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist");
  272. echo "Run By Root: launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist\n";
  273. }
  274. else if ($arg2 == 'newFiles') {
  275. $time = new stdClass();
  276. $time->start = time();
  277. self::newFilesAction();
  278. $time->end = time();
  279. // TODO: print operation time if DBG
  280. }
  281. else if ($arg2 == 'nextTask') {
  282. $time = new stdClass();
  283. $time->start = time();
  284. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
  285. self::installTable();
  286. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">installTable DONE</pre>';}
  287. self::generateTasksNewRecords();
  288. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksNewRecords DONE</pre>';}
  289. self::generateTasksUpdated();
  290. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksUpdated DONE</pre>';}
  291. $limit = V::get('_limit', 1, $_GET, 'int');
  292. for ($i = 0; $i < $limit; $i++) {
  293. $time->cur = time();
  294. if ($time->cur - $time->start > 60 * 5) {
  295. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">Force-break time('.($time->cur - $time->start).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';echo'</pre>';}
  296. break;
  297. }
  298. $task = self::nextTaskAction();
  299. if (!$task) {
  300. break;
  301. }
  302. }
  303. }
  304. else if ($arg2 == 'testErrorLog') {
  305. echo "display_errors: " . ini_get("display_errors") . "\n";
  306. echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
  307. echo "log_errors: " . ini_get("log_errors") . "\n";
  308. echo "error_reporting: " . ini_get("error_reporting") . "\n";
  309. echo "error_log: " . ini_get("error_log") . "\n";
  310. trigger_error("Notice: Test Error Log", E_USER_NOTICE);
  311. }
  312. else if ($arg2 == 'users') {
  313. self::usersAction();
  314. }
  315. else if ($arg2 == 'usersAll') {
  316. self::usersAllAction();
  317. }
  318. else if ($arg2 == 'SyncPermsCustomTables') {
  319. $DBG_TIME = true;
  320. $dbgTime = new stdClass();
  321. $dbgTime->startTime = microtime(true);
  322. $dbgTime->lastTime = $dbgTime->startTime;
  323. $customSync = new SyncPermsCustomTables();
  324. // TODO: $customSync->run();
  325. $customSync->fetchConfig();
  326. if ($DBG_TIME) {
  327. $dbgTime->curTime = microtime(true);
  328. trigger_error("DBG:time after-fetchConfig (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  329. $dbgTime->lastTime = $dbgTime->curTime;
  330. }
  331. $customSync->installTable();
  332. if ($DBG_TIME) {
  333. $dbgTime->curTime = microtime(true);
  334. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  335. $dbgTime->lastTime = $dbgTime->curTime;
  336. }
  337. $rowId = (int)$arg3;
  338. if ($rowId > 0) {
  339. $customSync->executeTask('DEALS_TABLE', $rowId);
  340. }
  341. else {
  342. $customSync->generateTasksNewRecords();
  343. if ($DBG_TIME) {
  344. $dbgTime->curTime = microtime(true);
  345. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  346. $dbgTime->lastTime = $dbgTime->curTime;
  347. }
  348. $customSync->generateTasksUpdated();
  349. if ($DBG_TIME) {
  350. $dbgTime->curTime = microtime(true);
  351. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  352. $dbgTime->lastTime = $dbgTime->curTime;
  353. }
  354. $customSync->newFilesAction();
  355. if ($DBG_TIME) {
  356. $dbgTime->curTime = microtime(true);
  357. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  358. $dbgTime->lastTime = $dbgTime->curTime;
  359. }
  360. $limit = 1000;
  361. for ($i = 0; $i < $limit; $i++) {
  362. $loopTasksFired = 0;
  363. foreach ($customSync->_tbls as $tblName => $tblConf) {
  364. $task = $customSync->nextTaskAction($tblName);
  365. if ($DBG_TIME) {
  366. $dbgTime->curTime = microtime(true);
  367. trigger_error("DBG:time after-nextTaskAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  368. $dbgTime->lastTime = $dbgTime->curTime;
  369. }
  370. if (!$task) {
  371. // TODO: rm $tblName from config to prevent searching for task in next loops
  372. unset($customSync->_tbls[$tblName]);
  373. continue;
  374. }
  375. $loopTasksFired++;
  376. }
  377. if (!$loopTasksFired) {
  378. if ($DBG_TIME) {
  379. $dbgTime->curTime = microtime(true);
  380. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  381. $dbgTime->lastTime = $dbgTime->curTime;
  382. }
  383. break;
  384. }
  385. $i += $loopTasksFired;
  386. }
  387. }
  388. $dbgTime->endTime = microtime(true);
  389. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  390. }
  391. else {
  392. $DBG_TIME = false;
  393. $DBG_MEMORY = false;
  394. $dbgTime = new stdClass();
  395. $dbgTime->start = time();
  396. $dbgTime->startTime = microtime(true);
  397. $dbgTime->lastTime = $dbgTime->startTime;
  398. self::installTable();
  399. if ($DBG_TIME) {
  400. $dbgTime->curTime = microtime(true);
  401. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  402. $dbgTime->lastTime = $dbgTime->curTime;
  403. }
  404. self::generateTasksNewRecords();
  405. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
  406. if ($DBG_TIME) {
  407. $dbgTime->curTime = microtime(true);
  408. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  409. $dbgTime->lastTime = $dbgTime->curTime;
  410. }
  411. self::generateTasksUpdated();
  412. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
  413. if ($DBG_TIME) {
  414. $dbgTime->curTime = microtime(true);
  415. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  416. $dbgTime->lastTime = $dbgTime->curTime;
  417. }
  418. $dbgTime->cur = time();
  419. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  420. trigger_error("Error: time end after-init " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  421. return;
  422. }
  423. self::newFilesAction();
  424. if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
  425. if ($DBG_TIME) {
  426. $dbgTime->curTime = microtime(true);
  427. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  428. $dbgTime->lastTime = $dbgTime->curTime;
  429. }
  430. $limit = 100;
  431. for ($i = 0; $i < $limit; $i++) {
  432. $dbgTime->cur = time();
  433. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  434. trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  435. return;
  436. }
  437. $task = self::nextTaskAction();
  438. if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
  439. if ($DBG_TIME) {
  440. $dbgTime->curTime = microtime(true);
  441. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  442. $dbgTime->lastTime = $dbgTime->curTime;
  443. }
  444. if (!$task) {
  445. $dbgTime->cur = time();
  446. break;
  447. }
  448. }
  449. $customSync = new SyncPermsCustomTables();
  450. $customSync->run();
  451. $dbgTime->cur = time();
  452. $dbgTime->endTime = microtime(true);
  453. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  454. if ($DBG_TIME) {
  455. $dbgTime->curTime = microtime(true);
  456. trigger_error("DBG:time sync end OK (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  457. $dbgTime->lastTime = $dbgTime->curTime;
  458. }
  459. }
  460. }
  461. public static function newFilesAction() {
  462. $task = self::getTaskNewFiles();
  463. $taskResult = self::fixLastModifiedFiles($task);
  464. self::saveTask(-1);
  465. }
  466. public static function nextTaskAction() {
  467. $task = self::getTask();
  468. if (!$task) {
  469. return false;
  470. }
  471. self::executeTask($task);
  472. /*
  473. if (isset($task->A_SYNC_RESULT->total)
  474. && isset($task->A_SYNC_RESULT->lastDone)
  475. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  476. ) {
  477. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  478. } else {
  479. self::saveTask($task->ID_PROJECT);
  480. }
  481. */
  482. self::saveTask($task->ID_PROJECT);
  483. return $task;
  484. }
  485. public static function generateTasksUpdated() {
  486. $db = DB::getDB();
  487. if (!$db) die("DB Error: No DB! L." . __LINE__);
  488. $sqlTest = "select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
  489. from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  490. where
  491. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  492. and (
  493. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  494. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  495. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  496. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  497. )
  498. ";
  499. $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  500. set
  501. s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
  502. , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
  503. , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
  504. , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
  505. , s.`A_SYNCHRONIZED`=0
  506. where
  507. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  508. and (
  509. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  510. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  511. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  512. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  513. )
  514. ";
  515. $res = $db->query($sql);
  516. }
  517. public static function generateTasksNewRecords() {
  518. $db = DB::getDB();
  519. if (!$db) die("DB Error: No DB! L." . __LINE__);
  520. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  521. values (-1, '', '', '', '');
  522. ";
  523. $res = $db->query($sql);
  524. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  525. select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
  526. from `IN7_MK_BAZA_DYSTRYBUCJI` as p
  527. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
  528. where p.`A_STATUS`!='DELETED'
  529. ";
  530. $res = $db->query($sql);
  531. }
  532. /**
  533. * Znajdź najstarszy aktualizowany projekt.
  534. */
  535. public static function getTask() {
  536. $task = null;
  537. $db = DB::getDB();
  538. if (!$db) die("DB Error: No DB! L." . __LINE__);
  539. $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
  540. if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0){
  541. $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
  542. }
  543. $sql = "select s.*
  544. , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
  545. , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
  546. , p.`A_CLASSIFIED` as p__A_CLASSIFIED
  547. , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  548. , p.`M_DIST_DESC` as p__M_DIST_DESC
  549. , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
  550. , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
  551. from `_SYNC_FILE_PERMS` as s
  552. left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
  553. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
  554. where
  555. {$sqlWhereProjID}
  556. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  557. limit 1
  558. ";
  559. $res = $db->query($sql);
  560. if ($r = $db->fetch($res)) {
  561. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  562. $task = $r;
  563. }
  564. return $task;
  565. }
  566. public static function getTaskNewerUsers() {
  567. $task = null;
  568. $db = DB::getDB();
  569. if (!$db) die("DB Error: No DB! L." . __LINE__);
  570. $sql = "select s.*
  571. from `_SYNC_FILE_PERMS` as s
  572. where s.`ID_PROJECT`=-2
  573. ";
  574. $res = $db->query($sql);
  575. if ($r = $db->fetch($res)) {
  576. $task = $r;
  577. }
  578. if (!$task) {
  579. $task = new stdClass();
  580. $task->ID_PROJECT = -2;
  581. $task->A_SYNC_RESULT = new stdClass();
  582. $task->A_LAST_SYNC = '';//mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  583. //$task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  584. }
  585. return $task;
  586. }
  587. public static function getTaskNewFiles() {
  588. $task = null;
  589. $db = DB::getDB();
  590. if (!$db) die("DB Error: No DB! L." . __LINE__);
  591. $sql = "select s.*
  592. from `_SYNC_FILE_PERMS` as s
  593. where s.`ID_PROJECT`=-1
  594. ";
  595. $res = $db->query($sql);
  596. if ($r = $db->fetch($res)) {
  597. $task = $r;
  598. }
  599. if (!$task) {
  600. $task = new stdClass();
  601. $task->ID_PROJECT = -1;
  602. $task->A_SYNC_RESULT = new stdClass();
  603. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  604. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  605. }
  606. return $task;
  607. }
  608. public static function saveTask($idProject, $taskDone = 1, $result = null) {
  609. $task = null;
  610. $db = DB::getDB();
  611. if (!$db) die("DB Error: No DB! L." . __LINE__);
  612. $sqlResult = '';
  613. if ($result) {
  614. $resultJson = json_encode($result);
  615. $resultJson = $db->_($resultJson);
  616. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  617. }
  618. $sql = "update `_SYNC_FILE_PERMS` as s
  619. set
  620. s.`A_LAST_SYNC`=NOW()
  621. , s.`A_SYNCHRONIZED`={$taskDone}
  622. {$sqlResult}
  623. where s.`ID_PROJECT`={$idProject}
  624. ";
  625. $res = $db->query($sql);
  626. return $task;
  627. }
  628. public static function executeTask(&$task) {
  629. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  630. $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
  631. $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  632. $project = new stdClass();
  633. $project->ID = $task->ID_PROJECT;
  634. $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
  635. $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
  636. $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
  637. $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
  638. $project->M_DIST_DESC = $task->p__M_DIST_DESC;
  639. $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
  640. $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
  641. $folderConf = FoldersConfig::getAll($confTblName);
  642. $uploader = new FileUploader($confTblName, $project);
  643. $errMsg = '';
  644. if (!$uploader->setConfig($folderConf, $errMsg)) {
  645. trigger_error("Error: folders config!", E_USER_NOTICE);
  646. die("Error: folders config!");
  647. }
  648. $uploader->findFolder();
  649. $mainFolder = $uploader->getDestFolder();
  650. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  651. if (!$mainFolder) {
  652. $mainFolder = $uploader->generateFolderName();
  653. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  654. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  655. mkdir($mainFolderPath, 0770, true);
  656. @chmod($mainFolderPath, 0770);
  657. if (!file_exists($mainFolderPath)) {
  658. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  659. return false;
  660. }
  661. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  662. $file = new stdClass();
  663. $file->name = '.';
  664. $file->path = '.';
  665. //$file->owner = '';
  666. //$file->group = '';
  667. //$file->perms = '';
  668. $file->isDir = true;
  669. $file->permsExt = array();
  670. $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
  671. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  672. }
  673. else {
  674. $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
  675. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProject (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  676. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  677. $folderPismaPath = "{$mainFolderPath}/_PISMA";
  678. // if folder _PISMA not exists then create
  679. $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
  680. $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
  681. if (!empty($cmdKorepList)) {
  682. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProjectKoresp (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdKorepList);echo'</pre>';}
  683. foreach ($cmdKorepList as $vCmd) {
  684. $cmdList[] = $vCmd;
  685. }
  686. }
  687. }
  688. if (!empty($cmdList)) {
  689. foreach ($cmdList as $vCmd) {
  690. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  691. exec($vCmd, $out, $outValue);
  692. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  693. if ($outValue != 0) {
  694. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  695. }
  696. }
  697. }
  698. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  699. }
  700. public static function getActiveLoginList() {
  701. static $activeLoginList;
  702. if (!is_array($activeLoginList)) {
  703. $activeLoginList = array();
  704. $db = DB::getDB();
  705. if (!$db) {
  706. die('DB Error!');
  707. }
  708. $sql = "select u.`ADM_ACCOUNT`
  709. from `ADMIN_USERS` as u
  710. where u.`A_STATUS` = 'NORMAL'
  711. ";
  712. $res = $db->query($sql);
  713. while ($r = $db->fetch($res)) {
  714. $activeLoginList[] = $r->ADM_ACCOUNT;
  715. }
  716. }
  717. return $activeLoginList;
  718. }
  719. public static function isActiveUser($login) {
  720. $activeLoginList = self::getActiveLoginList();
  721. return in_array($login, $activeLoginList);
  722. }
  723. public static function getRequiredPermsExtByRecord($project) {
  724. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  725. $requirePermsExt = array();
  726. if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
  727. // TODO: group PODMIOT
  728. $requirePermsExt["group:workgroup"] = array('write', 'read');
  729. }
  730. else {
  731. if ($project->L_APPOITMENT_USER) {
  732. if (self::isActiveUser($project->L_APPOITMENT_USER)) {
  733. $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
  734. } else {
  735. // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
  736. }
  737. }
  738. if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
  739. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
  740. }
  741. else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
  742. $requirePermsExt["group:workgroup"] = array('write', 'read');
  743. }
  744. else {
  745. if ($project->A_ADM_COMPANY) {
  746. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
  747. }
  748. if ($project->A_CLASSIFIED) {
  749. $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
  750. }
  751. }
  752. }
  753. // add parent owner
  754. if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
  755. if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
  756. $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  757. } else {
  758. // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
  759. }
  760. }
  761. // add user:_www perms read, write
  762. $requirePermsExt["user:_www"] = array('write', 'read');
  763. return $requirePermsExt;
  764. }
  765. /**
  766. * Used for files added/modified by samba/afp.
  767. *
  768. * @return TODO: object to store in task->A_SYNC_RESULT
  769. */
  770. public static function fixLastModifiedFiles($task) {
  771. $db = DB::getDB();
  772. if (!$db) die("DB Error: No DB! L." . __LINE__);
  773. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  774. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  775. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  776. $foundProjectFiles = array();
  777. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  778. //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  779. exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  780. if (!empty($filesWithPerms)) {
  781. $filesWithPermsTree = array();
  782. $lastName = '';
  783. foreach ($filesWithPerms as $line) {
  784. if (substr($line, 0, 1) == '-') {// file name
  785. $fileParts = array();
  786. $filePartsArr = explode(' ', $line);
  787. $lastInd = 0;
  788. foreach ($filePartsArr as $vPart) {
  789. if ($lastInd > 7) {// file name
  790. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  791. $lastInd++;
  792. }
  793. else if (!empty($vPart) || $vPart === '0') {
  794. $fileParts[] = $vPart;
  795. $lastInd++;
  796. }
  797. }
  798. $file = new stdClass();
  799. if (!isset($fileParts[8])) {
  800. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  801. //continue;
  802. }
  803. $file->name = end($fileParts);
  804. $file->path = end($fileParts);
  805. //$file->owner = $fileParts[2];
  806. //$file->group = $fileParts[3];
  807. //$file->perms = $fileParts[0];
  808. $file->isDir = (substr($line, 0, 1) == 'd');
  809. $file->permsExt = array();
  810. $filesWithPermsTree[$file->name] = $file;
  811. $lastName = $file->name;
  812. }
  813. else if (substr($line, 0, 1) == ' ') {// extended perm line
  814. if ($lastName == '..') {
  815. continue;
  816. }
  817. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  818. }
  819. else {// parse error
  820. $lastName = '..';
  821. }
  822. }
  823. foreach ($filesWithPermsTree as $vFile) {
  824. $vFile->path = ltrim($vFile->path, './');
  825. $vFile->path = explode('/', $vFile->path);
  826. $vFile->projectFolder = array_shift($vFile->path);
  827. $vFile->path = implode('/', $vFile->path);
  828. $projId = explode('.', $vFile->projectFolder);
  829. $projId = reset($projId);
  830. if (is_numeric($projId) && $projId > 0) {
  831. $foundProjectFiles[$projId][] = $vFile;
  832. }
  833. }
  834. }
  835. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  836. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectFiles);echo'</pre>';}
  837. if (!empty($foundProjectFiles)) {
  838. $sql = "select p.`ID`
  839. , p.`L_APPOITMENT_USER`
  840. , p.`A_ADM_COMPANY`
  841. , p.`A_CLASSIFIED`
  842. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  843. from IN7_MK_BAZA_DYSTRYBUCJI as p
  844. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  845. where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
  846. ";
  847. $res = $db->query($sql);
  848. while ($r = $db->fetch($res)) {
  849. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  850. foreach ($foundProjectFiles[$r->ID] as $vFile) {
  851. $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
  852. if (!empty($cmdList)) {
  853. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  854. foreach ($cmdList as $vCmd) {
  855. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  856. exec($vCmd, $out, $outValue);
  857. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  858. if ($outValue != 0) {
  859. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  860. }
  861. }
  862. } else {
  863. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  864. }
  865. }
  866. }
  867. }
  868. }
  869. public static function fixProjectKoresp($project, $folderPismaPath) {
  870. $db = DB::getDB();
  871. if (!$db) die("DB Error: No DB! L." . __LINE__);
  872. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  873. $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
  874. $pismaList = array();
  875. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  876. $sql = "select k.`ID`
  877. , k.`K_TYP_KORESP`
  878. from `IN7_DZIENNIK_KORESP` as k
  879. where k.`ID_PROJECT`={$project->ID}
  880. order by k.`ID` DESC
  881. limit 100
  882. ";
  883. $res = $db->query($sql);
  884. while ($r = $db->fetch($res)) {
  885. $pismaList[$r->ID] = $r->K_TYP_KORESP;// TODO: K_TYP_KORESP not used
  886. }
  887. if (empty($pismaList)) {
  888. return false;
  889. }
  890. $lsCmd = array();
  891. $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
  892. foreach ($pismaList as $kID => $vTyp) {
  893. $lsCmd[] = "{$kID}.*/";
  894. }
  895. if (empty($lsCmd)) {
  896. return false;
  897. }
  898. $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
  899. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Koreps lsCmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lsCmd);echo'</pre>';}
  900. exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
  901. $filesWithPermsTree = array();
  902. if (!empty($filesWithPerms)) {
  903. $lastName = '';
  904. $folderParent = '';
  905. foreach ($filesWithPerms as $line) {
  906. if (substr($line, 0, 1) == '-') {// file name
  907. $fileParts = array();
  908. $filePartsArr = explode(' ', $line);
  909. $lastInd = 0;
  910. foreach ($filePartsArr as $vPart) {
  911. if ($lastInd > 7) {// file name
  912. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  913. $lastInd++;
  914. }
  915. else if (!empty($vPart) || $vPart === '0') {
  916. $fileParts[] = $vPart;
  917. $lastInd++;
  918. }
  919. }
  920. $file = new stdClass();
  921. if (!isset($fileParts[8])) {
  922. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  923. //continue;
  924. }
  925. $file->name = end($fileParts);
  926. $file->path = array();
  927. if ($folderParent) $file->path[] = $folderParent;
  928. $file->path[] = end($fileParts);
  929. $file->path = implode('/', $file->path);
  930. //$file->owner = $fileParts[2];
  931. //$file->group = $fileParts[3];
  932. //$file->perms = $fileParts[0];
  933. $file->isDir = (substr($line, 0, 1) == 'd');
  934. $file->permsExt = array();
  935. $filesWithPermsTree[$file->name] = $file;
  936. $lastName = $file->name;
  937. }
  938. else if (substr($line, 0, 1) == ' ') {// extended perm line
  939. if ($lastName == '..') {
  940. continue;
  941. }
  942. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  943. }
  944. else if (substr($line, -1) == ':') {// folder
  945. $folderParent = trim(substr($line, 0, -1), '/');
  946. }
  947. else if (substr($line, 0, 5) == 'total') {
  948. continue;
  949. }
  950. else if (empty($line)) {
  951. $folderParent = '';
  952. continue;
  953. }
  954. else {// parse error
  955. $lastName = '..';
  956. }
  957. }
  958. }
  959. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  960. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPermsTree);echo'</pre>';}
  961. $cmdList = array();
  962. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  963. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  964. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
  965. if (!empty($cmdFile)) {
  966. foreach ($cmdFile as $vCmd) {
  967. $cmdList[] = $vCmd;
  968. }
  969. }
  970. // if folder _PISMA not exists then create
  971. $fname = explode('/', $vFile->path);
  972. $fname = end($fname);
  973. $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
  974. }
  975. return $cmdList;
  976. }
  977. /*
  978. * Not used.
  979. */
  980. public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
  981. if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  982. if (isset($task->A_SYNC_RESULT->total)) {
  983. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
  984. if (!empty($filesTotal)) {
  985. $filesTotal = reset($filesTotal);
  986. $filesTotal = intval(trim($filesTotal));
  987. $task->A_SYNC_RESULT->total = $filesTotal;
  988. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  989. }
  990. }
  991. }
  992. }
  993. public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
  994. $time = time();
  995. if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  996. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: pomin - za dużo plików ('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  997. //return false;
  998. }
  999. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">r('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1000. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  1001. $filesWithPerms = array();
  1002. $cmd = " ls -Rlea . ";
  1003. if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1004. if (isset($task->A_SYNC_RESULT->total)) {
  1005. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">A_SYNC_RESULT (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("A_SYNC_RESULT[total]={$task->A_SYNC_RESULT->total}");echo'</pre>';}
  1006. if ($task->A_SYNC_RESULT->total > 1000) {
  1007. $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
  1008. if ($lastDone > 0) {
  1009. $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
  1010. $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
  1011. } else {
  1012. $task->A_SYNC_RESULT->lastDone = 1000;
  1013. $cmd = " find . -type f | head -1000 | xargs ls -le ";
  1014. }
  1015. }
  1016. }
  1017. }
  1018. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ");echo'</pre>';}
  1019. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
  1020. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';}
  1021. $filesWithPermsTree = array();
  1022. $lastName = '';
  1023. $folderParent = '';
  1024. foreach ($filesWithPerms as $line) {
  1025. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  1026. $fileParts = array();
  1027. $filePartsArr = explode(' ', $line);
  1028. $lastInd = 0;
  1029. foreach ($filePartsArr as $vPart) {
  1030. if ($lastInd > 7) {// file name
  1031. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1032. $lastInd++;
  1033. }
  1034. else if (!empty($vPart) || $vPart === '0') {
  1035. $fileParts[] = $vPart;
  1036. $lastInd++;
  1037. }
  1038. }
  1039. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  1040. $lastName = '..';
  1041. continue;
  1042. }
  1043. $file = new stdClass();
  1044. if (!isset($fileParts[8])) {
  1045. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1046. //continue;
  1047. }
  1048. $file->name = end($fileParts);
  1049. $file->path = array();
  1050. if ($folderParent) $file->path[] = $folderParent;
  1051. $file->path[] = end($fileParts);
  1052. $file->path = implode('/', $file->path);
  1053. //$file->owner = $fileParts[2];
  1054. //$file->group = $fileParts[3];
  1055. //$file->perms = $fileParts[0];
  1056. $file->isDir = (substr($line, 0, 1) == 'd');
  1057. $file->permsExt = array();
  1058. $filesWithPermsTree[$file->name] = $file;
  1059. $lastName = $file;
  1060. }
  1061. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1062. if ($lastName == '..') {
  1063. continue;
  1064. }
  1065. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1066. }
  1067. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  1068. $folderParent = substr($line, 2, -1);
  1069. }
  1070. else if (substr($line, 0, 5) == 'total') {
  1071. continue;
  1072. }
  1073. else if (empty($line)) {
  1074. $folderParent = '';
  1075. continue;
  1076. }
  1077. }
  1078. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  1079. // check perms
  1080. /*
  1081. files:
  1082. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  1083. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  1084. R read, execute, readattr, readextattr, readsecurity
  1085. dir:
  1086. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  1087. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  1088. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  1089. */
  1090. $cmdList = array();
  1091. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1092. if (false) {
  1093. // TODO: $kFileName == '_PISMA' - readonly
  1094. // TODO: $vFile->path => _PISMA/...
  1095. }
  1096. else {
  1097. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
  1098. if (!empty($cmdFile)) {
  1099. foreach ($cmdFile as $vCmd) {
  1100. $cmdList[] = $vCmd;
  1101. }
  1102. }
  1103. }
  1104. }
  1105. return $cmdList;
  1106. }
  1107. public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1108. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1109. $cmdList = array();
  1110. $vReqPermsExt = array();
  1111. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1112. $vReqPermsExt[$kPermObj] = array();
  1113. foreach ($vPerms as $vPerm) {
  1114. if ($vFile->isDir) {
  1115. if ($vPerm == 'read') {
  1116. $vReqPermsExt[$kPermObj]['list'] = 0;
  1117. $vReqPermsExt[$kPermObj]['search'] = 0;
  1118. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1119. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1120. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1121. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1122. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1123. }
  1124. else if ($vPerm == 'write') {
  1125. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1126. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1127. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1128. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1129. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1130. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1131. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1132. }
  1133. }
  1134. else {
  1135. if ($vPerm == 'read') {
  1136. $vReqPermsExt[$kPermObj]['read'] = 0;
  1137. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1138. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1139. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1140. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1141. }
  1142. else if ($vPerm == 'write') {
  1143. $vReqPermsExt[$kPermObj]['write'] = 0;
  1144. $vReqPermsExt[$kPermObj]['append'] = 0;
  1145. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1146. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1147. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1148. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1149. }
  1150. }
  1151. }
  1152. }
  1153. $permsToRemove = array();
  1154. foreach ($vFile->permsExt as $vPermExtLine) {
  1155. $vPermExtArr = explode(' ', $vPermExtLine);
  1156. $vPermExt = new stdClass();
  1157. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1158. $vPermExt->permObj = $vPermExtArr[1];
  1159. $vPermExt->perms = '';
  1160. if (count($vPermExtArr) == 4) {
  1161. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1162. }
  1163. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1164. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1165. }
  1166. else {
  1167. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1168. continue;
  1169. }
  1170. $permFound = false;
  1171. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1172. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1173. foreach ($vPerms as $kPerm => $vPermChecked) {
  1174. if (in_array($kPerm, $vPermExt->perms)) {
  1175. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1176. $permFound = true;
  1177. }
  1178. }
  1179. }
  1180. }
  1181. if (!$permFound) {
  1182. $permsToRemove[] = $vPermExt->nr;
  1183. }
  1184. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1185. }
  1186. if (!empty($permsToRemove)) {
  1187. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1188. $permsToRemove = array_reverse($permsToRemove);
  1189. foreach ($permsToRemove as $vPermInd) {
  1190. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1191. }
  1192. }
  1193. $permsToAdd = array();
  1194. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1195. foreach ($vPerms as $kPerm => $vPermChecked) {
  1196. if (!$vPermChecked) {
  1197. $permsToAdd[$kPermObj][$kPerm] = 1;
  1198. }
  1199. }
  1200. }
  1201. if (!empty($permsToAdd)) {
  1202. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1203. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1204. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1205. }
  1206. }
  1207. return $cmdList;
  1208. }
  1209. /**
  1210. * @returns array - last modified project ids.
  1211. */
  1212. public static function fixLastModifiedByFiles() {// TODO: RMME
  1213. $db = DB::getDB();
  1214. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1215. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByFiles");echo'</pre>';}
  1216. /*
  1217. * $ man find:
  1218. -newer file
  1219. True if the current file has a more recent last modification time than file.
  1220. -newerXY file
  1221. True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
  1222. or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
  1223. ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
  1224. tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
  1225. *
  1226. * $ man chmod:
  1227. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
  1228. *
  1229. * chmod -a "admin allow write" file1 # remove line
  1230. * chmod -a# 1 file1 # remove line at position 1
  1231. *
  1232. * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
  1233. */
  1234. // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
  1235. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  1236. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  1237. $foundProjectIds = array();
  1238. $lastRunDate = self::getLastRunDate();
  1239. exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
  1240. if (!empty($foundPaths)) {
  1241. foreach ($foundPaths as $path) {
  1242. $path = ltrim($path, './');
  1243. $folder = explode('/', $path);
  1244. $folder = reset($folder);
  1245. $projId = explode('.', $folder);
  1246. $projId = reset($projId);
  1247. if (is_numeric($projId)) {
  1248. $foundProjectIds[$projId] = $folder;
  1249. }
  1250. }
  1251. }
  1252. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundPaths (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundPaths);echo'</pre>';}
  1253. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectIds);echo'</pre>';}
  1254. if (!empty($foundProjectIds)) {
  1255. $sql = "select p.`ID`
  1256. , p.`L_APPOITMENT_USER`
  1257. , p.`A_ADM_COMPANY`
  1258. , p.`A_CLASSIFIED`
  1259. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1260. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1261. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1262. where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
  1263. ";
  1264. $res = $db->query($sql);
  1265. while ($r = $db->fetch($res)) {
  1266. $mainFolder = $foundProjectIds[$r->ID];
  1267. $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
  1268. if (!empty($cmdList)) {
  1269. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1270. } else {
  1271. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1272. }
  1273. }
  1274. }
  1275. return array_keys($foundProjectIds);
  1276. }
  1277. public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
  1278. $db = DB::getDB();
  1279. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1280. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByDB");echo'</pre>';}
  1281. $sqlWhereAdd = '';
  1282. if (!empty($fixedProjIds)) {
  1283. $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
  1284. }
  1285. $projectList = array();
  1286. $lastRunDate = self::getLastRunDate();
  1287. $sql = "select p.`ID`
  1288. , p.`L_APPOITMENT_USER`
  1289. , p.`A_ADM_COMPANY`
  1290. , p.`A_CLASSIFIED`
  1291. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1292. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1293. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1294. where
  1295. ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
  1296. or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
  1297. )
  1298. {$sqlWhereAdd}
  1299. ";
  1300. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1301. $res = $db->query($sql);
  1302. while ($r = $db->fetch($res)) {
  1303. $projectList[$r->ID] = $r;
  1304. }
  1305. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">projectList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($projectList);echo'</pre>';}
  1306. }
  1307. public static function getLastRunDate() {// TODO: RMME
  1308. if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
  1309. // Format: 2013-10-07 23:46
  1310. if (strlen($argFromDate) == 16
  1311. && substr($argFromDate, 4, 1) == '-'
  1312. && substr($argFromDate, 7, 1) == '-'
  1313. && substr($argFromDate, 10, 1) == '-'
  1314. && substr($argFromDate, 13, 1) == ':'
  1315. && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
  1316. ) {
  1317. $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
  1318. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1319. }
  1320. }
  1321. if (!$lastRunDate) {
  1322. $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
  1323. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1324. }
  1325. //$lastRunDate = '2013-09-01 01:00';
  1326. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
  1327. return $lastRunDate;
  1328. }
  1329. public static function usersAction() {
  1330. $task = self::getTaskNewerUsers();
  1331. $users = self::getUsersNewerThen($task->A_LAST_SYNC);
  1332. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1333. self::saveTask(-2);
  1334. }
  1335. public static function usersAllAction() {
  1336. /*
  1337. * DBU - DB User LDU - LDAP User
  1338. * DBG - DB Group LDG - LDAP Group
  1339. *
  1340. * DBU - ADMIN_USERS
  1341. * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
  1342. *
  1343. * 1. fetch DB Users
  1344. * ? only active users (A_STATUS == 'NORMAL')
  1345. * 2. fetch LDAP Users
  1346. *
  1347. * DBU.ADM_ACCOUNT == LDU.uid
  1348. * DBG.A_LDAP_GID == LDG.gidNumber
  1349. *
  1350. * TODO: $group createLdapGroup()
  1351. *
  1352. */
  1353. Lib::loadClass('UsersHelper');
  1354. $users = self::getUsersAll();
  1355. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">users count('.count($users).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1356. $allLdapUsers = UsersHelper::getLDAPUsersAll();
  1357. $ldapUsers = array();
  1358. foreach ($allLdapUsers as $vLdapUser) {
  1359. $ldapUsers[$vLdapUser->uid] = $vLdapUser;
  1360. }
  1361. unset($allLdapUsers);
  1362. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUsers count('.count($ldapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUsers);echo'</pre>';
  1363. foreach ($users as $kLogin => $vUser) {
  1364. if ($vUser->A_STATUS == 'NORMAL') {
  1365. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1366. echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
  1367. }
  1368. else {
  1369. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
  1370. }
  1371. }
  1372. else if ($vUser->A_STATUS == 'DELETED') {
  1373. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1374. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
  1375. }
  1376. else {
  1377. //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
  1378. }
  1379. }
  1380. }
  1381. }
  1382. public static function getUsersNewerThen($datetime) {
  1383. $users = array();
  1384. $db = DB::getDB();
  1385. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1386. $sqlWhereAdd = "";
  1387. if ($datetime) {
  1388. $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
  1389. } else {
  1390. // TODO: error datetime not set
  1391. }
  1392. $sql = "select u.ID
  1393. , u.`ADM_ACCOUNT`
  1394. , u.`ADM_NAME`
  1395. , u.`A_STATUS`
  1396. from `ADMIN_USERS` as u
  1397. where
  1398. u.`A_STATUS` in('NORMAL', 'DELETED')
  1399. ";
  1400. $res = $db->query($sql);
  1401. while ($r = $db->fetch($res)) {
  1402. $users[$r->ADM_ACCOUNT] = $r;
  1403. }
  1404. return $users;
  1405. }
  1406. public static function getUsersAll() {
  1407. $users = array();
  1408. $db = DB::getDB();
  1409. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1410. $sql = "select u.ID
  1411. , u.`ADM_ACCOUNT`
  1412. , u.`ADM_NAME`
  1413. , u.`A_STATUS`
  1414. from `ADMIN_USERS` as u
  1415. where
  1416. u.`A_STATUS` in('NORMAL', 'DELETED')
  1417. ";
  1418. $res = $db->query($sql);
  1419. while ($r = $db->fetch($res)) {
  1420. $users[$r->ADM_ACCOUNT] = $r;
  1421. }
  1422. return $users;
  1423. }
  1424. }
  1425. class SyncPermsCustomTables {
  1426. public $_tbls;
  1427. private $_db;
  1428. private $_syncTblName = '_SYNC_TABLE_FILE_PERMS';
  1429. private $_activeLoginList;
  1430. public function run() {
  1431. if (!$this->fetchConfig()) return;
  1432. $this->installTable();
  1433. $this->generateTasksNewRecords();
  1434. $this->generateTasksUpdated();
  1435. $this->newFilesAction();
  1436. $limit = 100;
  1437. for ($i = 0; $i < $limit; $i++) {
  1438. $loopTasksFired = 0;
  1439. foreach ($this->_tbls as $tblName => $tblConf) {
  1440. $task = $this->nextTaskAction($tblName);
  1441. if (!$task) {
  1442. // TODO: rm $tblName from config to prevent searching for task in next loops
  1443. unset($this->_tbls[$tblName]);
  1444. continue;
  1445. }
  1446. $loopTasksFired++;
  1447. }
  1448. if (!$loopTasksFired) break;
  1449. $i += $loopTasksFired;
  1450. }
  1451. }
  1452. public function fetchConfig() {
  1453. $this->_db = DB::getDB();
  1454. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1455. $tbls = array();
  1456. $sql = "select c.`CONF_VAL` as tbl_names
  1457. from `CRM_CONFIG` as c
  1458. where c.`CONF_KEY`='_SYNC_TABLE_FILE_PERMS__TablesList'
  1459. ";
  1460. $res = $this->_db->query($sql);
  1461. while ($r = $this->_db->fetch($res)) {
  1462. if (!empty($r->tbl_names)) {
  1463. $tbls = explode("\n", $r->tbl_names);
  1464. }
  1465. }
  1466. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', $tbls) . "]\n";
  1467. $configTbls = array();
  1468. Lib::loadClass('FoldersConfig');
  1469. if (!empty($tbls)) {
  1470. $folderConfAll = FoldersConfig::getRawData();
  1471. foreach ($tbls as $tblName) {
  1472. $tblName = trim($tblName);
  1473. if (empty($tblName)) continue;
  1474. $confTblName = "{$tblName}_COLUMN";
  1475. if (FoldersConfig::hasConfig($confTblName)) {
  1476. $configTbls[$tblName] = FoldersConfig::getAll($confTblName);
  1477. }
  1478. }
  1479. }
  1480. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', array_keys($configTbls)) . "]\n";
  1481. if (!empty($configTbls)) {
  1482. $this->_tbls = $configTbls;
  1483. }
  1484. return $this->_tbls;
  1485. }
  1486. public function installTable() {
  1487. if (!$this->_tbls) return;
  1488. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1489. $sql = "
  1490. CREATE TABLE IF NOT EXISTS `{$this->_syncTblName}` (
  1491. `ID` int(11) NOT NULL AUTO_INCREMENT,
  1492. `TBL_NAME` varchar(64),
  1493. `TBL_ID` int(11) NOT NULL,
  1494. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  1495. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  1496. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  1497. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  1498. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  1499. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  1500. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  1501. `A_POMIN_SYNC` tinyint(1) NOT NULL DEFAULT '0',
  1502. PRIMARY KEY (`ID`),
  1503. UNIQUE KEY `TBL` (`TBL_NAME`, `TBL_ID`)
  1504. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  1505. ";
  1506. $this->_db->query($sql);
  1507. if ($this->_db->has_errors()) {
  1508. print_r($this->_db->get_errors());
  1509. }
  1510. }
  1511. public function generateTasksNewRecords() {
  1512. if (!$this->_tbls) return;
  1513. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1514. $sqlValues = array();
  1515. foreach ($this->_tbls as $tblName => $tblConf) {
  1516. $sqlValues[] = "('{$tblName}', -1, '', '', '', '')";
  1517. }
  1518. $sqlValues = implode(',', $sqlValues);
  1519. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1520. values {$sqlValues};
  1521. ";
  1522. $res = $this->_db->query($sql);
  1523. if ($this->_db->has_errors()) {
  1524. print_r($this->_db->get_errors());
  1525. }
  1526. foreach ($this->_tbls as $tblName => $tblConf) {
  1527. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1528. select '{$tblName}' as TBL_NAME
  1529. , t.`ID`, t.`L_APPOITMENT_USER`, t.`A_ADM_COMPANY`, t.`A_CLASSIFIED`
  1530. , '' as PARENT_L_APPOITMENT_USER -- pp.`L_APPOITMENT_USER`
  1531. from `{$tblName}` as t
  1532. where t.`A_STATUS`!='DELETED'
  1533. ";
  1534. $res = $this->_db->query($sql);
  1535. if ($this->_db->has_errors()) {
  1536. print_r($this->_db->get_errors());
  1537. }
  1538. }
  1539. }
  1540. public function generateTasksUpdated() {
  1541. if (!$this->_tbls) return;
  1542. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1543. foreach ($this->_tbls as $tblName => $tblConf) {
  1544. $sql = "update `{$this->_syncTblName}` as s
  1545. , `{$tblName}` as t
  1546. -- , `IN7_MK_BAZA_DYSTRYBUCJI` as pt
  1547. set
  1548. s.`L_APPOITMENT_USER`=t.`L_APPOITMENT_USER`
  1549. , s.`A_ADM_COMPANY`=t.`A_ADM_COMPANY`
  1550. , s.`A_CLASSIFIED`=t.`A_CLASSIFIED`
  1551. , s.`PARENT_L_APPOITMENT_USER`='' -- pt.`L_APPOITMENT_USER`
  1552. , s.`A_SYNCHRONIZED`=0
  1553. where
  1554. s.`TBL_ID`=t.`ID`
  1555. and s.`TBL_NAME`='{$tblName}'
  1556. -- and pt.`ID`=t.`P_ID`
  1557. and (
  1558. s.`L_APPOITMENT_USER`!=t.`L_APPOITMENT_USER`
  1559. or s.`A_ADM_COMPANY`!=t.`A_ADM_COMPANY`
  1560. or s.`A_CLASSIFIED`!=t.`A_CLASSIFIED`
  1561. -- or s.`PARENT_L_APPOITMENT_USER`!=pt.`L_APPOITMENT_USER`
  1562. )
  1563. ";
  1564. $res = $this->_db->query($sql);
  1565. if ($this->_db->has_errors()) {
  1566. print_r($this->_db->get_errors());
  1567. }
  1568. }
  1569. }
  1570. public function newFilesAction() {
  1571. if (!$this->_tbls) return;
  1572. foreach ($this->_tbls as $tblName => $tblConf) {
  1573. $task = $this->_getTaskNewFiles($tblName);
  1574. $taskResult = $this->_fixLastModifiedFiles($task);
  1575. $this->_saveTask($tblName, -1);
  1576. }
  1577. }
  1578. private function _getTaskNewFiles($tblName) {
  1579. $task = null;
  1580. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1581. $sql = "select s.*
  1582. from `{$this->_syncTblName}` as s
  1583. where s.`TBL_ID`=-1 and s.`TBL_NAME`='{$tblName}'
  1584. ";
  1585. $res = $this->_db->query($sql);
  1586. if ($r = $this->_db->fetch($res)) {
  1587. $task = $r;
  1588. }
  1589. if (!$task) {
  1590. $task = new stdClass();
  1591. $task->TBL_NAME = $tblName;
  1592. $task->TBL_ID = -1;
  1593. $task->A_SYNC_RESULT = new stdClass();
  1594. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  1595. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  1596. }
  1597. return $task;
  1598. }
  1599. private function _fixLastModifiedFiles($task) {
  1600. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1601. $tblName = $task->TBL_NAME;
  1602. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  1603. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1604. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1605. $record = null;
  1606. $folderConf = FoldersConfig::getAll($confTblName);
  1607. $uploader = new FileUploader($confTblName, $record);
  1608. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1609. trigger_error("Error: folders config!", E_USER_NOTICE);
  1610. die("Error: folders config!");
  1611. }
  1612. $hasRecordOwnFolder = $uploader->hasRecordOwnFolder();
  1613. $foundTblFiles = array();
  1614. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  1615. //exec("cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  1616. $filesWithPerms = array();
  1617. $cmd = "cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;";
  1618. exec($cmd, $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  1619. if (!empty($filesWithPerms)) {
  1620. $filesWithPermsTree = array();
  1621. $lastName = '';
  1622. foreach ($filesWithPerms as $line) {
  1623. if (substr($line, 0, 1) == '-') {// file name
  1624. $fileParts = array();
  1625. $filePartsArr = explode(' ', $line);
  1626. $lastInd = 0;
  1627. foreach ($filePartsArr as $vPart) {
  1628. if ($lastInd > 7) {// file name
  1629. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1630. $lastInd++;
  1631. }
  1632. else if (!empty($vPart) || $vPart === '0') {
  1633. $fileParts[] = $vPart;
  1634. $lastInd++;
  1635. }
  1636. }
  1637. $file = new stdClass();
  1638. if (!isset($fileParts[8])) {
  1639. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1640. //continue;
  1641. }
  1642. $file->name = end($fileParts);
  1643. $file->path = end($fileParts);
  1644. //$file->owner = $fileParts[2];
  1645. //$file->group = $fileParts[3];
  1646. //$file->perms = $fileParts[0];
  1647. $file->isDir = (substr($line, 0, 1) == 'd');
  1648. $file->permsExt = array();
  1649. $filesWithPermsTree[$file->name] = $file;
  1650. $lastName = $file->name;
  1651. }
  1652. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1653. if ($lastName == '..') {
  1654. continue;
  1655. }
  1656. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1657. }
  1658. else {// parse error
  1659. $lastName = '..';
  1660. }
  1661. }
  1662. foreach ($filesWithPermsTree as $vFile) {
  1663. $vFile->path = ltrim($vFile->path, './');
  1664. $vFile->path = explode('/', $vFile->path);
  1665. $vFile->recordFolder = array_shift($vFile->path);// $vFile->projectFolder -> recordFolder
  1666. $vFile->path = implode('/', $vFile->path);
  1667. // TODO: _getTableIdFromFolderName($task->TBL_NAME, $vFile->recordFolder);
  1668. $tblId = 0;
  1669. if ($hasRecordOwnFolder) {
  1670. $tblId = explode('.', $vFile->recordFolder);
  1671. $tblId = reset($tblId);
  1672. }
  1673. else {
  1674. $tblId = explode('.', $vFile->path);
  1675. $tblId = reset($tblId);
  1676. }
  1677. if (is_numeric($tblId) && $tblId > 0) {
  1678. $foundTblFiles[$tblId][] = $vFile;
  1679. }
  1680. }
  1681. }
  1682. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  1683. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundTblFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($foundTblFiles);echo'</pre>';}
  1684. if (!empty($foundTblFiles)) {
  1685. $rowsIds = array_keys($foundTblFiles);
  1686. $sql = "select t.`ID`
  1687. , t.`L_APPOITMENT_USER`
  1688. , t.`A_ADM_COMPANY`
  1689. , t.`A_CLASSIFIED`
  1690. -- , pt.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1691. from `{$task->TBL_NAME}` as t
  1692. -- left join `{$task->TBL_NAME}` as pt on (pt.ID=t.P_ID)
  1693. where t.`ID` in (" . implode(',', $rowsIds) . ")
  1694. ";
  1695. $res = $this->_db->query($sql);
  1696. while ($r = $this->_db->fetch($res)) {
  1697. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  1698. foreach ($foundTblFiles[$r->ID] as $vFile) {
  1699. $cmdList = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$vFile->recordFolder}", $r);
  1700. if (!empty($cmdList)) {
  1701. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1702. foreach ($cmdList as $vCmd) {
  1703. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  1704. exec($vCmd, $out, $outValue);
  1705. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  1706. if ($outValue != 0) {
  1707. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  1708. }
  1709. }
  1710. } else {
  1711. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  1712. }
  1713. }
  1714. }
  1715. }
  1716. }
  1717. private function _getRequiredPermsExtByRecord($record) {
  1718. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  1719. $requirePermsExt = array();
  1720. if (!$record->L_APPOITMENT_USER && !$record->A_ADM_COMPANY) {// no owner, no write group
  1721. // TODO: group PODMIOT
  1722. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1723. }
  1724. else {
  1725. if ($record->L_APPOITMENT_USER) {
  1726. if ($this->_isActiveUser($record->L_APPOITMENT_USER)) {
  1727. $requirePermsExt["user:{$record->L_APPOITMENT_USER}"] = array('write', 'read');
  1728. } else {
  1729. // TODO: trigger error $record->L_APPOITMENT_USER is not active user!
  1730. }
  1731. }
  1732. if (!empty($record->A_ADM_COMPANY) && $record->A_ADM_COMPANY == $record->A_CLASSIFIED) {
  1733. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('read', 'write');
  1734. }
  1735. else if (empty($record->A_ADM_COMPANY) && empty($record->A_CLASSIFIED)) {
  1736. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1737. }
  1738. else {
  1739. if ($record->A_ADM_COMPANY) {
  1740. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('write');
  1741. }
  1742. if ($record->A_CLASSIFIED) {
  1743. $requirePermsExt["group:{$record->A_CLASSIFIED}"] = array('read');
  1744. }
  1745. }
  1746. }
  1747. // add parent owner
  1748. if (!empty($record->PARENT_L_APPOITMENT_USER) && $record->PARENT_L_APPOITMENT_USER != $record->L_APPOITMENT_USER) {
  1749. if ($this->_isActiveUser($record->PARENT_L_APPOITMENT_USER)) {
  1750. $requirePermsExt["user:{$record->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  1751. } else {
  1752. // TODO: trigger error $record->PARENT_L_APPOITMENT_USER is not active user!
  1753. }
  1754. }
  1755. // add user:_www perms read, write
  1756. $requirePermsExt["user:_www"] = array('write', 'read');
  1757. return $requirePermsExt;
  1758. }
  1759. private function _fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1760. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1761. $cmdList = array();
  1762. $vReqPermsExt = array();
  1763. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1764. $vReqPermsExt[$kPermObj] = array();
  1765. foreach ($vPerms as $vPerm) {
  1766. if ($vFile->isDir) {
  1767. if ($vPerm == 'read') {
  1768. $vReqPermsExt[$kPermObj]['list'] = 0;
  1769. $vReqPermsExt[$kPermObj]['search'] = 0;
  1770. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1771. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1772. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1773. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1774. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1775. }
  1776. else if ($vPerm == 'write') {
  1777. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1778. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1779. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1780. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1781. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1782. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1783. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1784. }
  1785. }
  1786. else {
  1787. if ($vPerm == 'read') {
  1788. $vReqPermsExt[$kPermObj]['read'] = 0;
  1789. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1790. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1791. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1792. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1793. }
  1794. else if ($vPerm == 'write') {
  1795. $vReqPermsExt[$kPermObj]['write'] = 0;
  1796. $vReqPermsExt[$kPermObj]['append'] = 0;
  1797. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1798. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1799. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1800. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1801. }
  1802. }
  1803. }
  1804. }
  1805. $permsToRemove = array();
  1806. foreach ($vFile->permsExt as $vPermExtLine) {
  1807. $vPermExtArr = explode(' ', $vPermExtLine);
  1808. $vPermExt = new stdClass();
  1809. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1810. $vPermExt->permObj = $vPermExtArr[1];
  1811. $vPermExt->perms = '';
  1812. if (count($vPermExtArr) == 4) {
  1813. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1814. }
  1815. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1816. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1817. }
  1818. else {
  1819. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1820. continue;
  1821. }
  1822. $permFound = false;
  1823. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1824. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1825. foreach ($vPerms as $kPerm => $vPermChecked) {
  1826. if (in_array($kPerm, $vPermExt->perms)) {
  1827. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1828. $permFound = true;
  1829. }
  1830. }
  1831. }
  1832. }
  1833. if (!$permFound) {
  1834. $permsToRemove[] = $vPermExt->nr;
  1835. }
  1836. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1837. }
  1838. if (!empty($permsToRemove)) {
  1839. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1840. $permsToRemove = array_reverse($permsToRemove);
  1841. foreach ($permsToRemove as $vPermInd) {
  1842. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1843. }
  1844. }
  1845. $permsToAdd = array();
  1846. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1847. foreach ($vPerms as $kPerm => $vPermChecked) {
  1848. if (!$vPermChecked) {
  1849. $permsToAdd[$kPermObj][$kPerm] = 1;
  1850. }
  1851. }
  1852. }
  1853. if (!empty($permsToAdd)) {
  1854. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1855. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1856. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1857. }
  1858. }
  1859. return $cmdList;
  1860. }
  1861. private function _isActiveUser($usrLogin) {
  1862. $activeLoginList = $this->_fetchActiveLoginList();
  1863. return in_array($usrLogin, $activeLoginList);
  1864. }
  1865. public function _fetchActiveLoginList() {
  1866. if (!$this->_db) die('DB Error!');
  1867. if (!is_array($this->_activeLoginList)) {
  1868. $this->_activeLoginList = array();
  1869. $sql = "select u.`ADM_ACCOUNT`
  1870. from `ADMIN_USERS` as u
  1871. where u.`A_STATUS` = 'NORMAL'
  1872. ";
  1873. $res = $this->_db->query($sql);
  1874. while ($r = $this->_db->fetch($res)) {
  1875. $this->_activeLoginList[] = $r->ADM_ACCOUNT;
  1876. }
  1877. }
  1878. return $this->_activeLoginList;
  1879. }
  1880. private function _saveTask($tblName, $tblId, $taskDone = 1, $result = null) {
  1881. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1882. $sqlResult = '';
  1883. if ($result) {
  1884. $resultJson = json_encode($result);
  1885. $resultJson = $this->_db->_($resultJson);
  1886. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  1887. }
  1888. $sql = "update `{$this->_syncTblName}` as s
  1889. set
  1890. s.`A_LAST_SYNC`=NOW()
  1891. , s.`A_SYNCHRONIZED`={$taskDone}
  1892. {$sqlResult}
  1893. where s.`TBL_ID`={$tblId} and s.`TBL_NAME`='{$tblName}'
  1894. ";
  1895. $res = $this->_db->query($sql);
  1896. }
  1897. public function executeTask($tblName, $tblId) {
  1898. if (!$this->_tbls) return;
  1899. $task = $this->_getTask($tblName, $tblId);
  1900. if (!$task) return;
  1901. $this->_executeTask($task);
  1902. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1903. return $task;
  1904. }
  1905. public function nextTaskAction($tblName) {
  1906. if (!$this->_tbls) return;
  1907. $task = $this->_getTask($tblName);
  1908. if (!$task) return;
  1909. $this->_executeTask($task);
  1910. /*
  1911. if (isset($task->A_SYNC_RESULT->total)
  1912. && isset($task->A_SYNC_RESULT->lastDone)
  1913. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  1914. ) {
  1915. $this->_saveTask($task->TBL_NAME, $task->TBL_ID, 0, $task->A_SYNC_RESULT);
  1916. } else {
  1917. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1918. }
  1919. */
  1920. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1921. return $task;
  1922. }
  1923. private function _getTask($tblName, $tblId = null) {
  1924. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1925. $task = null;
  1926. $recordFieldList = $this->_getRecordFieldList($tblName);
  1927. $recordFieldList[] = 'L_APPOITMENT_USER';
  1928. $recordFieldList[] = 'A_ADM_COMPANY';
  1929. $recordFieldList[] = 'A_CLASSIFIED';
  1930. $sqlRecordFields = array();
  1931. foreach ($recordFieldList as $fldName) {
  1932. $sqlRecordFields[] = "t.`{$fldName}` as t__{$fldName}";
  1933. }
  1934. $sqlRecordFields = implode(',', $sqlRecordFields);
  1935. $sqlTblId = "and s.`TBL_ID`!=-1";
  1936. if ($tblId > 0) $sqlTblId = "and s.`TBL_ID`='{$tblId}'";
  1937. $sql = "select s.*
  1938. , {$sqlRecordFields}
  1939. -- , pt.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  1940. from `{$this->_syncTblName}` as s
  1941. left join `{$tblName}` as t on(t.`ID`=s.`TBL_ID`)
  1942. -- left join `{$tblName}` as pt on(pt.`ID`=t.`P_ID`)
  1943. where
  1944. s.`TBL_NAME`='{$tblName}'
  1945. {$sqlTblId}
  1946. and s.`A_SYNCHRONIZED`=0
  1947. and s.`A_POMIN_SYNC`=0
  1948. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  1949. limit 1
  1950. ";
  1951. $res = $this->_db->query($sql);
  1952. if ($r = $this->_db->fetch($res)) {
  1953. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  1954. $task = $r;
  1955. $task->record = new stdClass();
  1956. foreach ($recordFieldList as $fldName) {
  1957. $aliasFldName = "t__{$fldName}";
  1958. $task->record->{$fldName} = $task->{$aliasFldName};
  1959. unset($task->{$aliasFldName});
  1960. }
  1961. }
  1962. return $task;
  1963. }
  1964. private function _getRecordFieldList($tblName) {
  1965. if (empty($this->_tbls[$tblName])) return;
  1966. $conf = $this->_tbls[$tblName];
  1967. $fldNames = array();
  1968. $fldName = V::get("LOOKAT_FOLDER_VARNAME", '', $conf);
  1969. $fldName = trim($fldName);
  1970. if (!empty($fldName)) $fldNames[$fldName] = true;
  1971. for ($i = 1; $i < 5; $i++) {
  1972. $fldName = V::get("LOOKAT_FOLDER_VARNAME{$i}", '', $conf);
  1973. $fldName = trim($fldName);
  1974. if (!empty($fldName)) $fldNames[$fldName] = true;
  1975. $fldName = V::get("DEST_FOLDER_VARNAME{$i}", '', $conf);
  1976. $fldName = trim($fldName);
  1977. if (!empty($fldName)) $fldNames[$fldName] = true;
  1978. }
  1979. if (!in_array('ID', $fldNames)) {
  1980. $fldNames['ID'] = true;
  1981. }
  1982. return array_keys($fldNames);
  1983. }
  1984. private function _executeTask($task) {
  1985. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  1986. $DBG_TIME = false;
  1987. $dbgTime = new stdClass();
  1988. $dbgTime->startTime = microtime(true);
  1989. $dbgTime->lastTime = $dbgTime->startTime;
  1990. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1991. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1992. $record = $task->record;
  1993. $folderConf = FoldersConfig::getAll($confTblName);
  1994. $uploader = new FileUploader($confTblName, $record);
  1995. $errMsg = '';
  1996. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1997. trigger_error("Error: folders config!", E_USER_NOTICE);
  1998. die("Error: folders config!");
  1999. }
  2000. if ($DBG_TIME) {
  2001. $dbgTime->curTime = microtime(true);
  2002. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-FileUploader->setConfig" . "\n";
  2003. $dbgTime->lastTime = $dbgTime->curTime;
  2004. }
  2005. $uploader->findFolder();
  2006. $mainFolder = $uploader->getDestFolder();
  2007. if ($DBG_TIME) {
  2008. $dbgTime->curTime = microtime(true);
  2009. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]:time after-FileUploader->getDestFolder" . "\n";
  2010. $dbgTime->lastTime = $dbgTime->curTime;
  2011. }
  2012. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  2013. if (!$mainFolder) {
  2014. $mainFolder = $uploader->generateFolderName();
  2015. $mainFolderPath = rtrim($TBL_mount_point, '/') . '/' . $mainFolder;
  2016. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  2017. @mkdir($mainFolderPath, 0770, true);
  2018. @chmod($mainFolderPath, 0770);
  2019. if (!file_exists($mainFolderPath)) {
  2020. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  2021. return false;
  2022. }
  2023. $requirePermsExt = $this->_getRequiredPermsExtByRecord($record);
  2024. $file = new stdClass();
  2025. $file->name = '.';
  2026. $file->path = '.';
  2027. //$file->owner = '';
  2028. //$file->group = '';
  2029. //$file->perms = '';
  2030. $file->isDir = true;
  2031. $file->permsExt = array();
  2032. $cmdList = $this->_fixFilePerms($file, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $record);
  2033. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$record->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  2034. }
  2035. else {
  2036. $cmdList = $this->_fixRecord($record, $uploader, $mainFolder, $TBL_mount_point, $task);
  2037. }
  2038. if ($DBG_TIME) {
  2039. $dbgTime->curTime = microtime(true);
  2040. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-generate cmdList - mainFolder(" . (($mainFolder)? 1 : 0) . ")" . "\n";
  2041. $dbgTime->lastTime = $dbgTime->curTime;
  2042. }
  2043. if (!empty($cmdList)) {
  2044. foreach ($cmdList as $vCmd) {
  2045. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  2046. exec($vCmd, $out, $outValue);
  2047. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  2048. if ($outValue != 0) {
  2049. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  2050. }
  2051. }
  2052. }
  2053. if ($DBG_TIME) {
  2054. $dbgTime->curTime = microtime(true);
  2055. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-executed cmdList " . "\n";
  2056. $dbgTime->lastTime = $dbgTime->curTime;
  2057. }
  2058. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  2059. }
  2060. public function _fixRecord($r, $uploader, $mainFolder, $TBL_mount_point, &$task) {
  2061. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  2062. $DBG_TIME = false;
  2063. $dbgTime = new stdClass();
  2064. $dbgTime->startTime = microtime(true);
  2065. $dbgTime->lastTime = $dbgTime->startTime;
  2066. $filesWithPerms = array();
  2067. if ($uploader->hasRecordOwnFolder()) {
  2068. $cmd = " ls -Rlea . ";
  2069. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2070. exec($cmd, $filesWithPerms);
  2071. }
  2072. else {
  2073. $lookGlob = $uploader->getFileSearchRegex();
  2074. $cmd = " ls -Rlea {$lookGlob} ";
  2075. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2076. exec($cmd, $filesWithPerms);
  2077. }
  2078. //echo "\n-----------------------\n";
  2079. //echo "filesWithPerms: ";print_r($filesWithPerms);echo "\n";
  2080. if ($DBG_TIME) {
  2081. $dbgTime->curTime = microtime(true);
  2082. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} " . "\n";
  2083. $dbgTime->lastTime = $dbgTime->curTime;
  2084. }
  2085. $filesWithPermsTree = array();
  2086. $lastName = '';
  2087. $folderParent = '';
  2088. foreach ($filesWithPerms as $line) {
  2089. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  2090. $fileParts = array();
  2091. $filePartsArr = explode(' ', $line);
  2092. $lastInd = 0;
  2093. foreach ($filePartsArr as $vPart) {
  2094. if ($lastInd > 7) {// file name
  2095. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  2096. $lastInd++;
  2097. }
  2098. else if (!empty($vPart) || $vPart === '0') {
  2099. $fileParts[] = $vPart;
  2100. $lastInd++;
  2101. }
  2102. }
  2103. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  2104. $lastName = '..';
  2105. continue;
  2106. }
  2107. $file = new stdClass();
  2108. if (!isset($fileParts[8])) {
  2109. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  2110. //continue;
  2111. }
  2112. $file->name = end($fileParts);
  2113. $file->path = array();
  2114. if ($folderParent) $file->path[] = $folderParent;
  2115. $file->path[] = end($fileParts);
  2116. $file->path = implode('/', $file->path);
  2117. //$file->owner = $fileParts[2];
  2118. //$file->group = $fileParts[3];
  2119. //$file->perms = $fileParts[0];
  2120. $file->isDir = (substr($line, 0, 1) == 'd');
  2121. $file->permsExt = array();
  2122. $filesWithPermsTree[$file->name] = $file;
  2123. $lastName = $file;
  2124. }
  2125. else if (substr($line, 0, 1) == ' ') {// extended perm line
  2126. if ($lastName == '..') {
  2127. continue;
  2128. }
  2129. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  2130. }
  2131. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  2132. $folderParent = substr($line, 2, -1);
  2133. }
  2134. else if (substr($line, 0, 5) == 'total') {
  2135. continue;
  2136. }
  2137. else if (empty($line)) {
  2138. $folderParent = '';
  2139. continue;
  2140. }
  2141. }
  2142. //echo "filesWithPermsTree: ";print_r($filesWithPermsTree);echo "\n";
  2143. if ($DBG_TIME) {
  2144. $dbgTime->curTime = microtime(true);
  2145. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: parse cmd output" . "\n";
  2146. $dbgTime->lastTime = $dbgTime->curTime;
  2147. }
  2148. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  2149. // check perms
  2150. /*
  2151. files:
  2152. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  2153. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  2154. R read, execute, readattr, readextattr, readsecurity
  2155. dir:
  2156. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  2157. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  2158. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  2159. */
  2160. $cmdList = array();
  2161. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  2162. if (false) {
  2163. // TODO: $kFileName == '_PISMA' - readonly
  2164. // TODO: $vFile->path => _PISMA/...
  2165. }
  2166. else {
  2167. $cmdFile = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $r);
  2168. if (!empty($cmdFile)) {
  2169. foreach ($cmdFile as $vCmd) {
  2170. $cmdList[] = $vCmd;
  2171. }
  2172. }
  2173. }
  2174. }
  2175. //echo "cmdList: ";print_r($cmdList);echo "\n";
  2176. //echo "\n-----------------------\n";
  2177. if ($DBG_TIME) {
  2178. $dbgTime->curTime = microtime(true);
  2179. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: end" . "\n";
  2180. $dbgTime->lastTime = $dbgTime->curTime;
  2181. }
  2182. return $cmdList;
  2183. }
  2184. }
  2185. ?>